简体   繁体   中英

Getting loopback address instead of actual address?

/* program to print the IP address of the Host*/
------------------------------------------------

I am trying to print the Host IP address. when I execute the following program I am getting loop back address that is 127.0.0.1 . What should I change to get the actual IP address.

# include <stdio.h>
# include <stdlib.h>
# include <arpa/inet.h>
# include <string.h>
# include <sys/types.h>
# include <sys/socket.h>
# include <netdb.h>
# include <netinet/in.h>

int main ()     {

        void *addr;
        char ipstr[INET6_ADDRSTRLEN];
        int rv;
        struct addrinfo hints, *res, *p;

        memset ( &hints, 0, sizeof hints );
        hints.ai_family = AF_UNSPEC;
        hints.ai_socktype = SOCK_STREAM;
        //hints.ai_flags = AI_ADDRCONFIG;
        hints.ai_flags = AI_PASSIVE;

        if ((rv = getaddrinfo(NULL ,"3490"  , &hints, &res)) != 0) {
                fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
                return 1;
        }

        for(p = res;p != NULL; p = p->ai_next) {

                struct sockaddr_in *ipv4 = (struct sockaddr_in *)p->ai_addr;
                addr = &(ipv4->sin_addr);
                inet_ntop(p->ai_family, addr, ipstr, sizeof ipstr);
                printf(" %s\n",  ipstr);
        }

}

As long as your development machine is not connected to a network you'll get the loopback address (which is perfectly valid for local network, of course). As soon as you connect the machine to the network you can determine the "right" address. ipconfig , btw, behaves the same.

If you call getaddrinfo with NULL for the node name (first parameter) it is the same as when you call it with "localhost". You'll get the loopback IP. However, if you use the "real" hostname, you'll get the "real" ip.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM