我正在编写一个简单的网络应用程序,并且需要制作UDP数据包并将其发送到特定主机。
int main(void){
// Message to be sent.
char message[] = "This is something";
int sockfd = socket(AF_INET, SOCK_RAW, IPPROTO_UDP);
if(sockfd < 0){
perror("Error creating socket");
exit(1);
}
struct sockaddr_in this, other;
this.sin_family = AF_INET;
other.sin_family = AF_INET;
this.sin_port = htons(8080);
other.sin_port = htons(8000);
this.sin_addr.s_addr = INADDR_ANY;
other.sin_addr.s_addr = inet_addr("10.11.4.99");
if(bind(sockfd, (struct sockaddr *)&this, sizeof(this)) < 0){
printf("Bind failed\n");
exit(1);
}
char packet[64] = {0};
struct udphdr *udph = (struct udphdr *) packet;
strcpy(packet + sizeof(struct udphdr), message);
udph->uh_sport = htons(8080);
udph->uh_dport = htons(8000);
udph->uh_ulen = htons(sizeof(struct udphdr) + sizeof(message));
udph->uh_sum = 0;
if(sendto(sockfd, packet, udph->uh_ulen, 0, (struct sockaddr *) &other, sizeof(other)) < 0)
perror("Error");
else
printf("Packet sent successfully\n");
close(sockfd);
return 0;
}
一切正常,直到调用sendto()为止。sendto()提供“错误地址”。谁能指出我要去哪里了?将端口绑定到原始套接字是否有任何问题?
该代码将消息的长度(udph-> uh_len)转换为网络字节顺序(htons)。不需要,因为它是size_t的参数类型。仅端口号(在sockaddr结构中)需要htons转换。
udph->uh_ulen = sizeof(struct udphdr) + sizeof(message);
当前代码在uh_ulen中产生大量(> 8000),从而导致发送失败。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句