UDP Broadcast sendto failed:“network is unreachabl

2019-06-18 04:27发布

问题:

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.