gethostbyaddr returns 0

gethostbyaddr returns 0

本文关键字:returns gethostbyaddr      更新时间:2023-10-16

我有一个包含IP地址的变量。我正在尝试对此进行nslookup,而不是返回DNS名称,我得到0。我在Linux环境中。目标IP来自一个向量(字符串dest_IP=vector[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;
}

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

您不能将c-样式字符串(即null终止)直接传递给gethostbyaddr

您需要创建一个struct in_addr,并将指向所创建结构的指针作为第一个参数传递给gethostbyaddr。要从char const*生成struct in_addr,请使用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 %sn", ipstr, hp->h_name);
    

我该如何进行进一步检查以确定出了什么问题

如果使用gethostbyaddr返回NULL,则应通过查看变量h_errno来检查出了什么问题。

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

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

有关该问题的更多详细信息,请参阅您的手册。


您的代码片段完全错误

您提供的代码片段甚至没有编译,但您在某种程度上展示了您试图实现的目标,但我无法确定 这篇文章包含的细节应该被认为是"有根据的猜测"

OP改变了他的职位

gethostbyaddr在出现错误时返回一个空指针。错误可能是错误的IP地址、未知主机、DNS设置错误等。您需要检查实际的错误代码。在Winsock上,这意味着调用WSAGetLastError,而在POSIX上(我认为),您需要检查h_errno的值。(我在POSIX上可能错了,我在那里没有经验)

    class CIPManager
{
public:
    CIPManager()
    {
        WSADATA wsaData;
        int iResult;
        iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
        if (iResult != 0) {
            printf("WSAStartup failed: %dn", iResult);
            //return 1;
        }
    }
    bool getPCName(unsigned long ip,char* hostname)//string& strIP)
    {
        DWORD dwRetval;
        //char hostname[NI_MAXHOST];
        char servInfo[NI_MAXSERV];
        u_short port = 27015;
        //hostname=NULL;
        // Validate the parameters
        /*if (argc != 2) {
            printf("usage: %s IPv4 addressn", argv[0]);
            printf("  to return hostnamen");
            printf("       %s 127.0.0.1n", argv[0]);
            return 1;
        }*/
        // Initialize Winsock
        /*
        */
        //-----------------------------------------
        // Set up sockaddr_in structure which is passed
        // to the getnameinfo function
        saGNI.sin_family = AF_INET;
        saGNI.sin_addr.s_addr =ip;// inet_addr(strIP);
        saGNI.sin_port = htons(port);
        //-----------------------------------------
        // Call getnameinfo
        dwRetval = getnameinfo((struct sockaddr *) &saGNI,
            sizeof (struct sockaddr),
            hostname,
            NI_MAXHOST, servInfo, 
            NI_MAXSERV, NI_NUMERICSERV);
        if (dwRetval != 0) {
            printf("getnameinfo failed with error # %ldn", WSAGetLastError());
            //return 1;
            return NULL;
        } else {
        //  printf("getnameinfo returned hostname = %sn", hostname);
            //return hostname;
            return 1;
        }
    }
protected:
private:
    struct sockaddr_in saGNI;
};

使用getnameinfo是更好的解决方案!