gethostbyaddr 返回 0

SP3*_*8TR 2 c++

我有一个包含 IP 地址的变量。我试图对此进行 nslookup,而不是返回 DNS 名称,但我得到 0。我处于 Linux 环境中。目标IP来自向量(字符串dest_ip =向量[2])。

#include <stdio.h>
#include <iostream>
#include <string.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <vector>
#include <algorithm>
#include <iterator>
#include <sstream>

using namespace std;

void split(const std::string& str, std::vector<std::string>& v) {
    std::stringstream ss(str);
    ss >> std::noskipws;
    std::string field;
    char ws_delim;
    while(1) {
        if( ss >> field )
            v.push_back(field);
        else if (ss.eof())
            break;
        else
            v.push_back(std::string());
        ss.clear();
        ss >> ws_delim;
    }
}

int main()
{

  string input_line;

  while(cin){

  getline(cin, input_line);

   for(int i=0; input_line[i]; i++)
                      if(input_line[i] == ':') input_line[i] = ' ';
                     for(int i=0; input_line[i]; i++)
                      if(input_line[i] == '/') input_line[i] = ' ';

  std::vector<std::string> v;
  split(input_line, v);

  string dest_ip = v[4];

  struct hostent *he;
  int i,len,type;
  len = dest_ip.length();
  type=AF_INET;

  he = gethostbyaddr(dest_ip.c_str(),len,type);

  cout<<"Hostname: "<<he<<"\n";

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

同样,我得到的不是主机名,而是 0。

Fil*_*efp 6

您不能将c 风格字符串 (即以 null 结尾)直接传递给gethostbyaddr.

您需要创建一个struct in_addr并将指向创建的结构体的指针作为第一个参数传递给gethostbyaddr. struct in_addrchar const*use生成inet_aton.

以下示例取自man gethostbyaddr


例子

  • 打印出与特定 IP 地址关联的主机名:

    const char *ipstr = "127.0.0.1";
    struct in_addr ip;
    struct hostent *hp;
    
    if (!inet_aton(ipstr, &ip))
            errx(1, "can't parse IP address %s", ipstr);
    
    if ((hp = gethostbyaddr((const void *)&ip, sizeof ip, AF_INET)) == NULL)
            errx(1, "no name associated with %s", ipstr);
    
     printf("name associated with %s is %s\n", ipstr, hp->h_name);
    
    Run Code Online (Sandbox Code Playgroud)

我如何进行进一步检查以查明出了什么问题?

如果您使用gethostbyaddrreturn,NULL您应该通过查看变量来检查出了什么问题h_errno

h_errno可以具有以下定义值之一:

  1. HOST_NOT_FOUND
  2. TRY_AGAIN
  3. NO_RECOVERY
  4. NO_DATA

请查阅您的手册以获取有关该问题的更多详细信息。


你的片段完全错误..

您提供的代码片段甚至无法编译,但您在某种程度上显示了您想要完成的任务,但我无法确定这一点。 这篇文章包含应被视为“有根据的猜测”的细节。

OP改变了他的帖子..