Hostname vs. IP - address

前端 未结 2 1611
野的像风
野的像风 2021-02-14 07:56

I am currently implementing openssl into my application. My problem arose when I had to set the hostname, IP - address, and port of the BIO. I have always known ip and hostname

2条回答
  •  终归单人心
    2021-02-14 08:36

    A host name can have multiple IP addresses, but not the other way around. If you check out

    https://beej.us/guide/bgnet/html/multi/gethostbynameman.html

    you'll see that gethostbyname() returns a list of addresses for a particular host. To prove it, here's a small program:

    #include 
    #include 
    #include 
    #include 
    #include 
    
    int main(int argc, char** argv)
    {
        if (argc < 2)
        {
            printf("usage: %s hostname\n", argv[0]);
            return 0;
        }
    
        struct in_addr addr;
        struct hostent* he = gethostbyname(argv[1]);
    
        if (!he)
        {
            perror("gethostbyname");
            return 1;
        }
    
        printf("IP addresses for %s:\n\n", he->h_name);
    
        for (int i = 0; he->h_addr_list[i]; i++)
        {
            memcpy(&addr, he->h_addr_list[i], sizeof(struct in_addr));
            printf("%s\n", inet_ntoa(addr));
        }
    
        return 0;
    }
    

    Entering www.yahoo.com, I get the following:

    98.137.246.8
    98.137.246.7
    98.138.219.232
    98.138.219.231

提交回复
热议问题