分类: 系统运维
2009-06-08 10:52:55
现在需要在netfilter中实现UDP消息包的交互,使用Socket编程机制。
#include #include #include #include #include #include #include #include static struct socket *sock; static struct work_struct work; static int my_sendto(struct socket *sock, void * buff, size_t len, unsigned flags, struct sockaddr *addr, int addr_len) { struct kvec vec; struct msghdr msg; vec.iov_base=buff; vec.iov_len=len; memset(&msg, 0x00, sizeof(msg)); msg.msg_name=addr; msg.msg_namelen=addr_len; msg.msg_flags = flags | MSG_DONTWAIT; return kernel_sendmsg(sock, &msg, &vec, 1, len); } static char buffer[128]; static void sendmsg(void *dummy) { int n; struct sockaddr_in addr; memset(&addr, 0x00, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_port = htons(1000); addr.sin_addr.s_addr = in_aton("61.139.2.69"); n = my_sendto(sock, buffer, 128, 0, (struct sockaddr *)&addr, sizeof(addr)); printk("send %i bytes\n", n); } static int socket_init(void) { INIT_WORK(&work, sendmsg, NULL); sock_create_kern(PF_INET, SOCK_DGRAM, 0, &sock); //不知加了GFP_ATOMIC,之后还会不会阻塞!! //sock->sk->sk_allocation = GFP_ATOMIC; schedule_delayed_work(&work, 2 * HZ);//两秒后sendmsg在kevent kernel thread中被调用 return 0; } static void socket_exit(void) { sock_release(sock); } module_init(socket_init); module_exit(socket_exit); 我的是2.6.12的内核! 代码没有安全检查,在没有看到"send nnn bytes"之前不要rmmod. |