在 linux 程序员手册中,该函数具有以下声明:
struct hostent *gethostbyname(const char *name);
这意味着参数必须是 char 数组(或外行术语中的字符串)。调用函数时可以直接使用带引号的字符串,例如“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 数组作为参数传递给函数。