在Linux程序员手动的函数具有以下声明:
struct hostent *gethostbyname(const char *name);
这意味着该参数必须是一个字符数组(或字符串在外行而言)。在调用函数时,可以直接使用带引号的字符串,例如“yahoo.com”。
下面的代码是对的gethostbyname如何工作的工作例如:
#include <stdio.h>
#include <string.h>
#include <netdb.h>
int main(){
struct hostent* h=gethostbyname("yahoo.com");
printf("Hostname: %s\n", h->h_name);
printf("Address type #: %d\n", h->h_addrtype);
printf("Address length: %d\n", h->h_length);
char text[50]; // allocate 50 bytes (a.k.a. char array)
strcpy(text,"bing.ca"); //copy string "bing.ca" to first 7 bytes of the array
h=gethostbyname(text); //plug in the value into the function. text="bing.ca"
printf("Hostname: %s\n", h->h_name);
printf("Address type #: %d\n", h->h_addrtype);
printf("Address length: %d\n", h->h_length);
return 0;
}
我把它叫做两次。一次为yahoo.com,一次为bing.ca,我检索了主机名,地址类型号码和地址长度(这是存储IP所需的字节数)。
对于调用bing地址,我分配了一个char数组,填充一个字符串,然后将该char数组作为参数传递给该函数。
'gethostname()'是否返回有效的主机名?您不检查错误的返回值。无论如何,调用'gethostbyname()'来调用'gethostname()'所报告的主机名是没有意义的。这是检索本地计算机IP地址的常见错误指导方式。您应该使用'GetAdaptersInfo' /'GetAdaptersAddresses'(Windows),'getifaddrs()'(* Nix)或其他类似平台特定的函数直接枚举本地接口。 –
是的,gethostname返回正确的主机名,但gethostbyname总是返回null。 –
你真的想完成什么? 'gethostbyname()'执行DNS查找。根据您计算机的DNS设置,使用'gethostname()'报告的主机名不能保证返回有效的DNS结果。在某些平台上,使用本地主机名调用'gethostbyname()'将返回结果,在某些平台上不会。如果失败,请检查'WSAGetLastError()'/'h_errno'来找出原因。在任何情况下,反正'gethostbyname()'都不推荐使用,您应该使用'getaddrinfo()'代替。 –