IP address help

I’m having a major-league mind fart at the moment.

What is the name of the library routine that returns a computer’s public IP address?
Berkeley or Winsock version will do…

Using 127.0.0.1 will not work in this case, because the requirement is to send the public address as part of a message.

Is something like this what you had in mind?



                //get the address for this interface
                if(ioctl(sock, SIOCGIFADDR, &ifreq) != 0){
                        perror("ioctl");
                        return 1;
                }

                //print out the address
                saptr = (struct sockaddr_in *)&ifreq.ifr_addr;

                printf( "%-5s  ::  %3d.%3d.%3d.%3d
",
                                ifreq.ifr_name,
                                NIPQUAD(saptr->sin_addr.s_addr) );



That’ll work, but the point where I’m trying this is before any network stuff is set up in the program.

I also did a bit of Googling, and I can also do what I want with gethostbyname (I think).

I looked up gethostbyname and according to MSDN it has been replaced by getaddrinfo. MSDN says “If nodename is a machine name, machine permanent addresses are returned.” Seems like it will do what you want.

I’ve always used the socket method so I have no experience with getaddrinfo. I’m pretty sure what I posted won’t work until the interface is set up though.