linux原始套接字raw获取ip包,linux-kernel – Raw Socket Help:为什么内核UDP不接收原始套接字创建的UDP数据包?...

我正在研究原始套接字.我使用IP_HDRINCL选项来构建自己的IP头.在IP标头之后,我正在构建UDP标头.然后我将数据包发送到我系统的环回地址.我有另一个程序正在运行,它将捕获UDP数据包.为了检查数据包是否正确形成和接收,我正在运行另一个正在读取原始IP数据报的进程.我的问题是虽然第二个进程(读取原​​始数据报)运行良好(所有IP和UDP字段似乎都没问题),但第一个进程(接收UDP)没有收到我创建的任何数据包. IP头中的协议字段没问题,端口也匹配……

我使用的是Linux 2.6.35-22.

我想知道新内核中这是否正常?请检查下面的代码是否有任何错误.应该接收数据包的UDP进程正在侦听绑定到同一台机器上的端口50000的套接字…

unsigned short in_cksum(unsigned short *addr, int len)

{

int nleft = len;

int sum = 0;

unsigned short *w = addr;

unsigned short answer = 0;

while (nleft > 1) {

sum += *w++;

nleft -= 2;

}

if (nleft == 1) {

*(unsigned char *) (&answer) = *(unsigned char *) w;

sum += answer;

}

sum = (sum >> 16) + (sum & 0xFFFF);

sum += (sum >> 16);

answer = ~sum;

return (answer);

}

main()

{

int fd=socket(AF_INET,SOCK_RAW,IPPROTO_UDP);

int val=1;

int ret=setsockopt(fd,IPPROTO_IP,IP_HDRINCL,&val,sizeof(val));

char buf[8192];

/* create a IP header */

struct iphdr* ip=(struct iphdr*)buf;//(struct iphdr*) malloc(sizeof(struct iphdr));

ip->version=4;

ip->ihl=5;

ip->tos=0;

ip->id=0;

ip->frag_off=0;

ip->ttl=255;

ip->protocol=IPPROTO_UDP;

ip->check=0;

ip->saddr=inet_addr("1.2.3.4");

ip->daddr=inet_addr("127.0.0.1");

struct udphdr* udp=(struct udphdr*)(buf+sizeof(struct iphdr));//(struct udphdr*) malloc(sizeof(struct udphdr));

udp->source=htons(40000);

udp->dest=htons(50000);

udp->check=0;

char* data=(char*)buf+sizeof(struct iphdr)+sizeof(struct udphdr);strcpy(data,"Harry Potter and the Philosopher's Stone");

udp->len=htons(sizeof(struct udphdr)+strlen(data));

udp->check=in_cksum((unsigned short*) udp,8+strlen(data));

ip->tot_len=htons(sizeof(struct iphdr)+sizeof(struct udphdr)+strlen(data));

struct sockaddr_in d;

bzero(&d,sizeof(d));

d.sin_family=AF_INET;

d.sin_port=htons(50000);

inet_pton(AF_INET,"localhost",&d.sin_addr.s_addr);

while(1)

sendto(fd,buf,sizeof(struct iphdr)+sizeof(struct udphdr)+strlen(data),0,(struct sockaddr*) &d,sizeof(d));

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值