Linux网络编程:技术与优化全解析
1. 手动构建UDP数据包
在网络编程中,有时需要手动构建UDP数据包,包含IP头部。以下是一个示例代码:
6 memset(&ip, 0, sizeof(ip));
7 ip.version = 4;
8 ip.ihl = 5;
9 ip.tos = 0;
10 ip.tot_len = htons(sizeof(struct iphdr) + datalen);
11 ip.id = htons(54321);
12 ip.frag_off = 0;
13 ip.ttl = 255;
14 ip.protocol = IPPROTO_UDP;
15 ip.saddr = inet_addr("192.168.0.1");
16 ip.daddr = inet_addr("192.168.0.2");
17 ip.check = 0; // Kernel calculates checksum
18
19 if (sendto(sockfd, &ip, ip.tot_len, 0, (struct sockaddr *)&destination, sizeof(destination)) < 0) {
20 perror("Send failed");
21 }
在这段代码中, inet_addr() 函数将人类可读的IP地址转换为二进制形式。内核会计算校验和,因此将 ip.check 设置为0。
超级会员免费看
订阅专栏 解锁全文
4万+

被折叠的 条评论
为什么被折叠?



