【发布时间】:2011-04-16 20:01:47
【问题描述】:
我正在研究原始套接字。我使用 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));
}
【问题讨论】:
-
启动wireshark。他们甚至会撞到电线吗?
-
是的,它们是......并且它正确地将协议显示为 UDP,目标端口为 50000。但是,源端口被标记为“saftynetp”。它的正确值是 40000,但我不知道这是什么意思
-
捕获一个由socat或其他东西传输的真实UDP数据包,然后尝试伪造一个相同的数据包。确保检查所有内容,包括校验和。在数据包转储上运行像 meld 这样的差异程序效果很好。
标签: linux-kernel udp raw-sockets