gethostbyname in C

自古美人都是妖i 提交于 2019-11-30 12:36:13
#include <stdio.h>
#include <netdb.h>


int main(int argc, char *argv[])
{
    struct hostent *lh = gethostbyname("localhost");

    if (lh)
        puts(lh->h_name);
    else
        herror("gethostbyname");

    return 0;
}

It is not a very reliable way of determining the hostname, though it may sometimes work. (what it returns depends on how /etc/hosts is set up). If you have a line like:

127.0.0.1    foobar    localhost

...then it will return "foobar". If you have it the other way around though, which is also common, then it will just return "localhost". A more reliable way is to use the gethostname() function:

#include <stdio.h>
#include <unistd.h>
#include <limits.h>

int main(int argc, char *argv[])
{
    char hostname[HOST_NAME_MAX + 1];

    hostname[HOST_NAME_MAX] = 0;
    if (gethostname(hostname, HOST_NAME_MAX) == 0)
        puts(hostname);
    else
        perror("gethostname");

    return 0;
}

In C/UNIX, the equivalent would be something like:

#include <stdio.h>
#include <netdb.h>

int main (int argc, char *argv[]) {
    struct hostent *hstnm;
    if (argc != 2) {
        fprintf(stderr, "usage: %s hostname\n", argv[0]);
        return 1;
    }
    hstnm = gethostbyname (argv[1]);
    if (!hstnm)
        return 1;
    printf ("Name: %s\n", hstnm->h_name);
    return 0;
}

and the proof that it works:

$ hstnm localhost
Name: demon-a21pht

But try it yourself. Provided you have the correct environment, it should be fine.

what is wrong?

h_name

The official name of the host (PC). If using the DNS or similar resolution system, it is the Fully Qualified Domain Name (FQDN) that caused the server to return a reply. If using a local hosts file, it is the first entry after the IPv4 address.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!