我正在研究原始套接字。我使用 IP_HDRINCL 选项来构建我自己的 IP 标头。在 IP 标头之后,我正在构建一个 UDP 标头。然后我将数据包发送到我系统的环回地址。我正在运行另一个程序,它将在 UDP 数据包到来时捕获它们。为了检查数据包是否正确形成和接收,我运行了另一个正在读取原始 IP 数据报的进程。我的问题是,虽然第二个进程(读取原始数据报)运行良好(所有 IP 和 UDP 字段似乎都正常),但第一个进程(接收 UDP)没有收到我创建的任何数据包。IP 标头中的协议字段没问题,端口也匹配...我使用的是 Linux 2.6.35-22。我想知道这在新内核中是否正常?请检查下面的代码是否有任何错误。
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));
}