troubleshooting Question

printf the IP address used to send a datagram

Avatar of jchristn123
jchristn123 asked on
22 Comments2 Solutions528 ViewsLast Modified:
How do I fetch the source IP address used out of a simple transmission?  For instance, if my UDP client code is:

int main(int argc, char *argv[])
   int sock, length, fromlen, n;
   struct sockaddr_in server;
   struct sockaddr_in from;
   char buf[1024];

   if (argc < 2) {
      fprintf(stderr, "ERROR, no port provided\n");
   sock=socket(AF_INET, SOCK_DGRAM, 0);
   if (sock < 0) error("Opening socket");
   length = sizeof(server);
   if (bind(sock,(struct sockaddr *)&server,length)<0)
   fromlen = sizeof(struct sockaddr_in);
   while (1) {
       n = recvfrom(sock,buf,1024,0,(struct sockaddr *)&from,&fromlen);
       if (n < 0) error("recvfrom");
       write(1,"Received a datagram: ",21);
       n = sendto(sock,"Got your message\n",17,
                  0,(struct sockaddr *)&from,fromlen);
       if (n  < 0) error("sendto");

How do I printf the IP address I used in sending the datagram as a string (not the destination address)?

Join the community to see this answer!
Join our exclusive community to see this answer & millions of others.
Unlock 2 Answers and 22 Comments.
Join the Community
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 2 Answers and 22 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros