当我通过下面的代码广播消息时,主机上的服务器也收到了消息,如何防止主机接收到它发送的消息?
是否可以更改代码上的某些内容或者使用类似的内容会更好if (strcmp(hostIP == IP_of_the_package) == 0) { <discard the msg>}
?主机从 DHCP 获取 IP,我该如何定义hostIP as a variable
和如何提取IP addr of the packet
?
void boardcast_msg(char *mess){
int sock;
struct sockaddr_in broadcastAddr;
char *broadcastIP;
unsigned short broadcastPort;
char *sendString;
int broadcastPermission;
int sendStringLen;
broadcastIP = "255.255.255.255";
broadcastPort = 33333;
sendString = mess; /* string to broadcast */
if ((sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0){
fprintf(stderr, "socket error");
exit(1);
}
broadcastPermission = 1;
if (setsockopt(sock, SOL_SOCKET, SO_BROADCAST, (void *) &broadcastPermission,sizeof(broadcastPermission)) < 0){
fprintf(stderr, "setsockopt error");
exit(1);
}
/* Construct local address structure */
memset(&broadcastAddr, 0, sizeof(broadcastAddr));
broadcastAddr.sin_family = AF_INET;
broadcastAddr.sin_addr.s_addr = inet_addr(broadcastIP);
broadcastAddr.sin_port = htons(broadcastPort);
sendStringLen = strlen(sendString);
/* Broadcast sendString in datagram to clients */
if (sendto(sock, sendString, sendStringLen, 0, (struct sockaddr *)&broadcastAddr, sizeof(broadcastAddr)) != sendStringLen){
fprintf(stderr, "sendto error");
exit(1);
}
}