각 네트워크 네임 스페이스에서 새 인스턴스 인 Linux 커널 모듈을 작성하는 방법은 무엇입니까?

mwarning

사용 struct pernet_operationsregister_pernet_subsys(..)리눅스 커널 모듈에서 네트워크 네임 스페이스 당 상태를 가지고있는 올바른 방법?

아니면 커널 모듈을 표시하고 각 네트워크 네임 스페이스에서 독립적 인 상태를 가질 수있는 방법이 있습니까?

mwarning

Linux 커널 모듈에는 하나의 상태 만 있습니다. 네트워크 네임 스페이스는 커널 모듈에서 명시 적으로 처리되어야합니다.

사용하는 주요 방법은 register_pernet_subsys, unregister_pernet_subsysnet_generic입니다.

다음은 커널 모듈의 예입니다.

#include <net/sock.h>
#include <net/netns/generic.h>
#include <net/net_namespace.h>
#include <linux/module.h>
#include <linux/skbuff.h>
#include <linux/pid_namespace.h>

/*
 * Per network namespace data
 */
struct ns_data {
  struct sock *sk;
};

/*
 * Index to store custom data for each network namespace.
 */
static unsigned int net_id;

/*
 * Called for every existing and added network namespaces
 */
static int __net_init ns_test_init(struct net *net)
{
  // create (if not present) and access data item in network namespace (net) using the id (net_id) 
  struct ns_data *data = net_generic(net, net_id);
  data->sk = -1; // initialize or example socket

  // ...

  return 0;
}

static void __net_exit ns_test_exit(struct net *net)
{
  // called when the network namespace is removed
  struct ns_data *data = net_generic(net, net_id);

  // close socket
  netlink_kernel_release(data->sk);
}

// callback to make the module network namespace aware
static struct pernet_operations net_ops __net_initdata = {
  .init = ns_test_init,
  .exit = ns_test_exit,
  .id = &net_id,
  .size = sizeof(struct ns_data),
};

static int __init netlink_test_init(void)
{
  printk(KERN_INFO "netlink_test: Init module\n");

  register_pernet_subsys(&net_ops);

  return 0;
}

static void __exit netlink_test_exit(void)
{
  printk(KERN_INFO "netlink_test: Exit module\n");

  unregister_pernet_subsys(&net_ops);
}

module_init(netlink_test_init);
module_exit(netlink_test_exit);

MODULE_LICENSE("GPL");

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

Related 관련 기사

뜨겁다태그

보관