我运行下面的服务器代码来打开一个 UDP 套接字。我的 linux 机器上有两个网络接口,两个接口连接到两个不同的网络。我希望程序监听指定的网络(通过分配 IP 地址),因此我在 UDP 套接字上分配了一个 IP 地址。
如果我使用servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
服务器能够接收广播和单播消息。但是,如果我定义了,servaddr.sin_addr.s_addr =inet_addr("10.0.0.6");
那么服务器可以接收源自的消息10.0.0.6
但不能接收广播10.0.0.255
消息(网络掩码是/24)。
这里是广播消息的代码,单播代码在这里。
是我分配的 IP 地址错误还是广播代码错误?
服务器代码是:
#define BUFSIZE 512
char *SERVER_IP = "10.0.0.6";
int main() {
int error_count=0, r=0, n=0;
int sockfd = 0;
struct sockaddr_in servaddr, cliaddr ,a ;
socklen_t len; //integer type of width of at least 32 bits
char mesg[1000];
sockfd = socket(AF_INET, SOCK_DGRAM, 0); // for datagram
while(sockfd < 0){ //error handling for socket opening
usleep(500000);
if (++error_count == 20){//10 times itteration
fprintf(stderr, "errno:%s - socket opening error - line 223\n ", strerror(errno));
exit(1);
}
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
}
error_count = 0;
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(33333); //server listens on this port
// servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_addr.s_addr =inet_addr(SERVER_IP);
printf("servaddr.sin_addr:%lu\n",servaddr.sin_addr );
printf("a.sin_addr:%lu\n",a.sin_addr );
r = bind(sockfd,(struct sockaddr *) &servaddr, sizeof(servaddr));
while(r < 0){ //error handling for socket binding
usleep(500000);
if (++error_count == 20){//10 times itteration
fprintf(stderr, "errno:%s - socket binding error - line 239\n ", strerror(errno));
exit(1);
}
r = bind(sockfd,(struct sockaddr *) &servaddr, sizeof(servaddr));
}
error_count = 0;
while(1){
len = sizeof(cliaddr);
next:
printf("server is listening\n");
n = recvfrom(sockfd, mesg, 1000, 0, (struct sockaddr *) &cliaddr, &len);
printf("line195: packet is received: %s\n", mesg);
if(n < 0){
fprintf(stderr, "recvfrom error occured - line254\n");
n = 0;
goto next;
}
}
return 0;
}
这是我的ifconfig -a wlan8
wlan8 Link encap:Ethernet HWaddr 64:70:02:18:1f:b6
inet addr:10.0.0.6 Bcast:10.0.0.255 Mask:255.255.255.0
inet6 addr: fe80::6670:2ff:fe18:1fb6/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:206 errors:0 dropped:0 overruns:0 frame:0
TX packets:297 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:37857 (37.8 KB) TX bytes:54526 (54.5 KB)