UDP Broadcast sendto failed:“network is unreachable” on linux 2.6.30

匿名 (未验证) 提交于 2019-12-03 00:48:01

问题:

I write a program using udp broadcast.Code segment as follows:

struct sockaddr_in broadcast_addr; socklen_t sock_len=sizeof(broadcast_addr);  bzero(&broadcast_addr,sock_len); broadcast_addr.sin_family=AF_INET; broadcast_addr.sin_port=12345; broadcast_addr.sin_addr.s_addr=inet_addr("255.255.255.255");  int fd=socket(AF_INET,SOCK_DGRAM,0); int broadcast_enable=1; setsockopt(fd,SOL_SOCKET,SO_BROADCAST,&broadcast_enable,sizeof(broadcast_enable));  uint8_t send_buf[100]; int ret=sendto(fd,send_buf,sizeof(send_buf),0,        (struct sockaddr*)&broadcast_addr,sock_len);   if(ret==-1)     perror("sendto failed"); 

output:

sendto failed: Network is unreachable 

But when I run "add default gateway" command like " route add default gw 10.10.10.111 ",the error disappears.When setting a new ipaddress to netdev,command as above should be ran,otherwise the error comes. Why? Thanks.

回答1:

Not sure why 255.255.255.255 isn't working for you. However, I've never used that as a broadcast IP myself. When I send a broadcast packet I usually derive the broadcast IP from my subnet mask, i.e. if your subnet mask is 255.255.255.0 (/24) and say your IP is 192.168.0.5, then to send a UDP broadcast your destination IP should be 192.168.0.255.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!