gethostbyname()函数返回null

时间:2015-11-17 01:31:30

标签: c sockets gethostbyname

我是网络编程新手,我正在尝试使用gethostbyname函数。当我输入一个字符串,如" www.yahoo.com"到gethostbyname函数它工作正常,但是当我输入一个char数组时,它总是返回null。

<base href="${ctx}/" > 

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

4 个答案:

答案 0 :(得分: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数组作为参数传递给函数。

答案 1 :(得分:0)

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

  1. DNS搜索列表通常应设置为包含主机名的域名 - 或者 - 主机名应该是完全限定的。
  2. 应为主机正确设置DNS。
  3. 这使得它根本不是C问题,而是服务器配置问题。关闭它。

答案 2 :(得分:0)

它返回NULL的一个很好的理由是因为你传递的主机名不正确。 有时即使 hostname -v 也不会提供正确的主机名。

请尝试以下操作:

cat /etc/hosts

这将显示输出为:

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

那个&#39; localhost&#39;在上面的输出中127.0.0.1旁边是您的主机名。这将与 gethostbyname 完美配合。

答案 3 :(得分:0)

               var hostBuilder = new HostBuilder()
               .ConfigureWebHostDefaults(webHost =>
               {
                   // Add TestServer
                   webHost.UseTestServer();
                   webHost.UseEnvironment(HostTestEnvironmentName.Get(inMemory: true))
                        .ConfigureEntityFrameworkForTesting(fixture)
                        .UseStartup<Startup>();
               });

                var host = hostBuilder.Start();
                var client = host.GetTestClient();

                _client = new FluentClient("http://a", client);

                _server = host.GetTestServer();
相关问题