Hello All,
I have a C program where I have created a UDP socket and bound to a particular ip address and a port number. As the program proceeds, msgs will be sent to different clients using the same socket, using the same port, but each has a different ip address. Is it possible to just overload the remoteServAddr1.sin_addr.s_addr with the desired ipaddress each time? Or is it important to bind the socket every time the ipaddress changes? If I call bind more than once, it gives me an error because the port is already in use.

struct hostent *h;
	sd = socket(AF_INET,SOCK_DGRAM,0);
      			printf(" cannot open socket \n");

   		h = gethostbyname(address[0]); /*the first ip address*/
      			printf("unknown host '%s' \n",  address[0]);

  		h->h_name,inet_ntoa(*(struct in_addr *)h->h_addr_list[0]));

   		remoteServAddr.sin_family = h->h_addrtype;
   		memcpy((char *) &remoteServAddr.sin_addr.s_addr, h->h_addr_list[0], h->h_length);
  		remoteServAddr.sin_port = htons(REMOTE_SERVER_PORT);

   		/* bind any port */
   		cliAddr.sin_family = AF_INET;
   		cliAddr.sin_addr.s_addr = htonl(INADDR_ANY);
   		cliAddr.sin_port = htons(REMOTE_SERVER_PORT);
   		rc = bind(sd, (struct sockaddr *) &cliAddr, sizeof(cliAddr));

     			printf("cannot bind port\n");

I want to change the ipaddress which will be stored as address[1]..So rather than address[0] in the above code, I want address[1]( socket,port being the same)..

Something like this

memcpy((char *) &remoteServAddr.sin_addr.s_addr, address[1], h1->h_length);
accept(sd, (struct sockaddr *)(&remoteServAddr), &cliLen);
printf("sending %s to %s on UDP port %u \n",connection,inet_ntoa(remoteServAddr.sin_addr), ntohs(remoteServAddr1.sin_port));
   rc = sendto(sd,connection,MAX_MSG, 0,(struct sockaddr *) &remoteServAddr, sizeof(remoteServAddr));

Is it possible at all??Any help would be appreciated..Right now its giving segmentation fault...

Salem commented: 20+ posts, and no code tags - when ya gonna learn??? -6

Recommended Answers

All 3 Replies

maybe i'm missing something, but UDP doesn't care what IP address is in the pseudo-header. it's a multicast protocol. anyone on the network can see and process the datagrams if they desire to do so.

For connection oriented UDP (like in your case), it is important to bind

If I bind to the same port number wont it give an error??

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.