的gethostbyname用C [英] gethostbyname in C

查看:192
本文介绍了的gethostbyname用C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道如何用C编写的应用程序,但我需要一个小的程序,做:

  LH =的gethostbyname(localhost的);
输出= LH-GT&; h_name;

输出变量要打印

以上code是PHP的MongoDB数据库驱动程序用来获取计算机的主机名(主机名是输入产生一个唯一的ID的一部分)。我怀疑,这将返回的主机名,所以我想一些证据。

任何code例子是最有帮助的。

快乐的日子,

马蒂奇


解决方案

 的#include<&stdio.h中GT;
#包括LT&;&netdb.h中GT;
INT主(INT ARGC,CHAR *的argv [])
{
    结构hostent * LH =的gethostbyname(localhost的);    如果(LH)
        看跌期权(LH-GT&; h_name);
    其他
        herror(的gethostbyname);    返回0;
}

这是不确定的主机名,虽然它可能有时工作的一个非常可靠的方法。 (它返回什么取决于如何 / etc / hosts中设置)。如果你有这样的一行:

  127.0.0.1本地主机FOOBAR

...那么它将返回FOOBAR。如果你有它虽然周围的其他方式,这也是常见的,那么它将只返回localhost的。一个更可靠的方法是使用的gethostname()功能:

 的#include<&stdio.h中GT;
#包括LT&;&unistd.h中GT;
#包括LT&;&limits.h中GT;INT主(INT ARGC,CHAR *的argv [])
{
    焦炭主机[HOST_NAME_MAX]    如果(获取主机名(主机名,sizeof的主机名)== 0)
        看跌期权(主机名);
    其他
        PERROR(获取主机名);    返回0;
}

I don't know how to write applications in C, but I need a tiny program that does:

lh = gethostbyname("localhost");
output = lh->h_name;

output variable is to be printed.

The above code is used in PHP MongoDB database driver to get the hostname of the computer (hostname is part of an input to generate an unique ID). I'm skeptical that this will return the hostname, so I'd like some proof.

Any code examples would be most helpful.

Happy day,

Matic

解决方案

#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];

    if (gethostname(hostname, sizeof hostname) == 0)
        puts(hostname);
    else
        perror("gethostname");

    return 0;
}

这篇关于的gethostbyname用C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆