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.