UDP broadcast in C

When I send a message using the code below, the server on the host machine also receives a message, how can I prevent the host machine from receiving the message that it sends?

Is it possible to change something in the code, or would it be better to use something like if (strcmp(hostIP == IP_of_the_package) == 0) { <discard the msg>}? the host machine receives an IP address from DHCP, how can I determine hostIP as a variableand how can I extract 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);
        }

}
+3
source share
4 answers

You are on the right track, you need to see if your packet is received from you, and then discard it.

- gethostname gethostbyname. , IP-. SO ( Google) .

+1

loopback, :

char loopch=0;

if (setsockopt(sd, IPPROTO_IP, IP_MULTICAST_LOOP,
               (char *)&loopch, sizeof(loopch)) < 0) {
  perror("setting IP_MULTICAST_LOOP:");
  close(sd);
  exit(1);
}

from: http://publib.boulder.ibm.com/infocenter/iseries/v5r3/index.jsp?topic=%2Frzab6%2Frzab6x1multicast.htm

+1

, .

iptables (TCP UDP ) , .

-1

recvfrom . .

, , (, ) IP- getifaddrs. POSIX.

-1

All Articles