获å–环回地å€è€Œä¸æ˜¯å®žé™…地å€ï¼Ÿ

时间:2013-11-26 08:49:36

标签: c sockets

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

我正在å°è¯•æ‰“å°ä¸»æœºIP地å€ã€‚当我执行以下程åºæ—¶  我得到的循环地å€æ˜¯127.0.0.1。我应该改å˜ä»€ä¹ˆæ¥èŽ·å¾—  实际IP地å€ã€‚

# 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);
        }

}

1 个答案:

答案 0 :(得分:0)

åªè¦æ‚¨çš„å¼€å‘机器未连接到网络,您就会获得环回地å€ï¼ˆå½“然,这对本地网络完全有效)。åªè¦å°†æœºå™¨è¿žæŽ¥åˆ°ç½‘络,就å¯ä»¥ç¡®å®šâ€œæ­£ç¡®â€çš„地å€ã€‚ ipconfig,顺便说一å¥ï¼Œè¡Œä¸ºç›¸åŒã€‚

如果为节点å称(第一个å‚数)调用getaddrinfo为NULL,则与使用“localhostâ€è°ƒç”¨å®ƒæ—¶ç›¸åŒã€‚你会得到环回IP。但是,如果您使用“真实â€ä¸»æœºå,您将获得“真正的â€IP。