我用udp广播写了一个程序。代码段如下:
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");
输出:
sendto failed: Network is unreachable
但是当我运行像“route add default gw 10.10.10.111”这样的“添加默认网关”命令时,错误消失了。当为netdev设置新的IP地址时,应该运行上述命令,否则错误来了。为什么?谢谢。