1

我是互联网编程新手,我正在尝试使用该gethostbyname()功能。当我向 gethostbyname 函数输入诸如“www.yahoo.com”之类的字符串时,它可以正常工作,但是当我输入 char 数组时,它总是会返回一个空缓冲区。

  char hostname[100];
  struct hostent* h;
  gethostname(hostname, sizeof hostname );
  printf("Hostname: %s\n", hostname);
  h = gethostbyname(hostname);

知道如何解决这个问题吗?

4

4 回答 4

1

您的服务器无法自行解析。“修复”此问题的最常见方法是将其自己的名称放入其主机文件中。虽然出于各种原因这是一个好主意,但真正应该解决的根本问题。

  1. DNS 搜索列表通常应该设置为包含主机名的域名 - 或者 - 主机名本身应该是完全限定的。
  2. 应为主机正确设置 DNS。

这使得它根本不是一个真正的 C 问题,而是一个服务器配置问题。那就关掉吧。

于 2015-11-17T02:23:40.263 回答
0

它返回 NULL 的一个很好的原因是因为您传递的主机名不正确。有时即使执行hostname -v也不会给出正确的主机名。

尝试以下操作:

cat /etc/hosts

这将显示您的输出为:

127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain

上面输出中 127.0.0.1 旁边的“localhost”是您的主机名。这将与gethostbyname完美配合。

于 2018-03-12T16:43:23.987 回答
0
WSADATA wsaData;
int error;
if ((error = WSAStartup(MAKEWORD(1, 1), &wsaData)) !=0)
{      
    printf("Error %d in WSAStartup, result will fail\n",error);
}   
char hostname[100];
struct hostent* h;
gethostname(hostname, sizeof hostname );
printf("Hostname: %s\n", hostname);
h = gethostbyname(hostname);
于 2020-03-03T09:07:43.633 回答
0

在 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 数组作为参数传递给函数。

于 2015-11-17T02:08:17.537 回答