gpt4 book ai didi

c++ - gethostbyaddr 返回 0

转载 作者:搜寻专家 更新时间:2023-10-31 00:01:30 24 4
gpt4 key购买 nike

我有一个包含 IP 地址的变量。我正在尝试对其进行 nslookup,而不是返回 DNS 名称,我得到 0。我在 Linux 环境中。目标 IP 来自 vector (字符串 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-style-string(即以 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 %s\n", ipstr, hp->h_name);

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

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

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

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

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


<罢工>您的代码段完全错误..

您提供的代码段甚至无法编译,但您以某种方式展示了您要完成的目标,但我无法确定这一点。 这篇文章包含的细节应被视为“有根据的猜测”。

OP 更改了他的帖子..

关于c++ - gethostbyaddr 返回 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9825114/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com