我有一个包含IP地址的变量。我正在尝试执行nslookup,返回的不是DNS名称,而是0。我在Linux环境中。目的IP来自一个向量(字符串dest_ip = vector2)。
#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。
发布于 2012-03-22 23:18:13
每当发生错误时,gethostbyaddr都会返回一个空指针。错误可能是错误的IP地址、未知主机、错误配置的DNS设置等。您需要检查实际的错误代码。在Winsock上,这将意味着调用WSAGetLastError,而在POSIX (我认为)上,您需要检查h_errno的值。(我可能在POSIX上错了,我在那里没有经验)
发布于 2013-05-23 10:18:15
class CIPManager
{
public:
CIPManager()
{
WSADATA wsaData;
int iResult;
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0) {
printf("WSAStartup failed: %d\n", 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 address\n", argv[0]);
printf(" to return hostname\n");
printf(" %s 127.0.0.1\n", 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 # %ld\n", WSAGetLastError());
//return 1;
return NULL;
} else {
// printf("getnameinfo returned hostname = %s\n", hostname);
//return hostname;
return 1;
}
}
protected:
private:
struct sockaddr_in saGNI;
};使用getnameinfo是一个更好的解决方案!
https://stackoverflow.com/questions/9825114
复制相似问题