I have a a variable that contains an IP address. I am trying to do an nslookup on that by instead of the DNS name being returned I get 0. I am in a Linux environment. Destination IP comes from a vector (string 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;
}
Again, instead of receiving the host name I get 0.
You cannot pass a c-style-string (ie. null-terminated) directly to
gethostbyaddr.You’ll need to create a
struct in_addrand pass a pointer to the created struct as first parameter togethostbyaddr. To generate astruct in_addrfrom achar const*useinet_aton.The below example is taken from man gethostbyaddr:
EXAMPLES
Print out the hostname associated with a specific IP address:
How do I do further checks to pin-point what went wrong?
If your use of
gethostbyaddrreturnsNULLyou should check what went wrong by looking at the variableh_errno.h_errnocan have one of the below defined values:HOST_NOT_FOUNDTRY_AGAINNO_RECOVERYNO_DATAPlease consult your manual for more details regarding the issue.
Your snippet is completely wrong..
The snippet provided by you doesn’t even compile, but you are in a way showing what you are trying to accomplish but I cannot know this for certain.
This post contains details that should be considered to be “educated guesses“.
OP changed his post..