getaddrinfo()返回环回地址

时间:2013-11-26 08:33:29

标签: c sockets

用于LAN中某个套接字通信应用程序的目标计算机的IPv4为192.168.98.91

当我尝试使用getaddrinfo()解析IPaddress时,它返回127.0.0.1

我如何获得192.168.98.91

我已在192.168.98.91文件中为myhost设置了/etc/hosts,并对myhost显示192.168.98.91作为IP地址进行了ping操作。

我的机器是CentOS6.4。

这是/ etc / hosts的设置。

192.168.98.91   myhost
127.0.0.1   myhost localhost.localdomain 

这是我的代码。

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

int
main(int argc,char *argv[]){
    int sock;
    struct addrinfo hints,*res;
    int n;
    int err;
    if(argc != 2){
        fprintf(stderr,"Usage : %s dst \n",argv[0]);
        return 1;
    } 
    memset(&hints,0,sizeof(hints));
    hints.ai_family = AF_UNSPEC; 
    hints.ai_socktype = SOCK_DGRAM;
    err = getaddrinfo(argv[1],"12345",&hints,&res);
    if(err != 0){
        perror("getaddrinfo");
        printf("getaddrinfo %s\n",strerror(errno));
        printf("getaddrinfo : %s \n",gai_strerror(err));
        return 1;
    }

    sock = socket(res->ai_family,res->ai_socktype,0);
    if(sock < 0){
        perror("socket");
        return 1;
    }
    {
        const char *ipverstr;
        switch (res->ai_family){
            case AF_INET:
                ipverstr = "IPv4";
                break;
            case AF_INET6:
                ipverstr = "IPv6";
                break;
            default:
                ipverstr = "unknown";
                break;            
        }
        printf("ipverstr = %s\n ",ipverstr);            
    }
    n = sendto(sock,"HELLO",5,0,res->ai_addr,res->ai_addrlen);
    //n = sendto(sock,"HELLO", 5, 0,(struct sockaddr *)addr, sizeof(addr));
    if(n<1){
        perror("sendto");
        {

        }
        return 1;
    }
    struct sockaddr_in *addr;
    addr = (struct sockaddr_in *)res->ai_addr; 
    printf("inet_ntoa(in_addr)sin = %s\n",inet_ntoa((struct in_addr)addr->sin_addr));

    printf("############ finish !! #######\n");
    close(sock);
    freeaddrinfo(res);
    return 0;
}

1 个答案:

答案 0 :(得分:5)

如果您使用getaddrinfo() ai_next struct addrinfo成员192.168.98.91返回myhost成员返回的结果链,那么 ... s = getaddrinfo(NULL, argv[1], &hints, &result); if (s != 0) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s)); exit(EXIT_FAILURE); } /* getaddrinfo() returns a list of address structures. Try each address until we successfully bind(2). If socket(2) (or bind(2)) fails, we (close the socket and) try the next address. */ for (rp = result; rp != NULL; rp = rp->ai_next) { /* Do something with rp->ai_family, rp->ai_socktype, ... */ } ... myhost也会获得/etc/hosts

在这里http://man7.org/linux/man-pages/man3/getaddrinfo.3.html您会找到一个完整的示例,其中还说明了如何执行此操作:

从上面的链接:

127.0.0.1   myhost localhost.localdomain 

127.0.0.1中的这一行删除getaddrinfo()

myhost
在向{{1}}提出要求时,

会导致{{1}}再次被{{1}}退回。