Hostname vs. IP - address

2019-04-08 17:47发布

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 to be the same thing. Could someone please explain the difference.

2条回答
等我变得足够好
2楼-- · 2019-04-08 17:49

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 <stdio.h>
#include <string.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <netinet/in.h>

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

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-04-08 18:03

A host name is a combination of the name of your machine and a domain name (e.g. machinename.domain.com). The purpose of a host name is readability - it's much easier to remember than an IP address. All hostnames resolve to IP addresses, so in many instances they are talked about like they are interchangeable.

查看更多
登录 后发表回答