我不知道如何用C编写应用程序,但我需要一个小程序:
lh = gethostbyname("localhost");
output = lh->h_name;
Run Code Online (Sandbox Code Playgroud)
输出变量将被打印.
以上代码用于PHP MongoDB数据库驱动程序以获取计算机的主机名(主机名是输入的一部分,用于生成唯一ID).我怀疑这将返回主机名,所以我想要一些证据.
任何代码示例都会非常有用.
愉快的一天.
caf*_*caf 20
#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;
}
Run Code Online (Sandbox Code Playgroud)
它不是一种确定主机名的非常可靠的方法,虽然它有时可行.(它返回的内容取决于如何/etc/hosts设置).如果你有一个像这样的行:
127.0.0.1 foobar localhost
Run Code Online (Sandbox Code Playgroud)
...然后它将返回"foobar".如果你有相反的方式,这也很常见,那么它只会返回"localhost".更可靠的方法是使用该gethostname()功能:
#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;
}
Run Code Online (Sandbox Code Playgroud)
在C/UNIX中,等效的类似于:
#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;
}
Run Code Online (Sandbox Code Playgroud)
并证明它有效:
$ hstnm localhost
Name: demon-a21pht
Run Code Online (Sandbox Code Playgroud)
但是亲自尝试一下.如果你有正确的环境,它应该没问题.