How to get ip to hostname ?

Hello everybody . I have a text file , I want to compare ip with in line text
This is file text
1
2
3
4
5
6
7
8
9
10
cplusplus.com

c++.com
C#.com

google.com



c+++.com

And this is my code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <iostream>
#include <fstream>
#include <string>
#include <conio.h>
using namespace std;


string getip(string hostname)
{
	//function get ip
}

void main ()
{
    string string_main="http://abc-xyz.com/www/~av.50.22.100.250?url.aspx/etc";
	
	int count=0;

	string string_sub;
	ifstream infile;
	infile.open ("E:\\test.txt");

        while(!infile.eof()) // To get you all the lines.
        {
	        getline(infile,string_sub); // Saves the line in string_sub.
	      //  cout<<string_sub<<"\n"; // Prints our string_sub.

			if (!string_sub.empty())
			{
				string temp=getip(string_sub); // get ip of string_sub on the text line by line 
				size_t result = string_main.find( temp ); //check string_sub on the text file line by line, comparable to string_main

				if( result != string::npos )  // if found
				{
					count+=1;
				}
			}
        }
	infile.close();
	//cout<< count <<"\n";
	if (count != 0)
	{
		cout << "Found\n";
	}
	else
	{
		cout << "Not found\n";
	}
getch();
}


Can you see it , How to create function get ip above ?
Thank you .










See gethostbyname()/gethostbyaddr()
Can you demo it in my code above . Thank
I have read this link http://msdn.microsoft.com/en-us/library/windows/desktop/ms738524%28v=vs.85%29.aspx and try it , But not untill .
Hi kbw
This link at linux. I test in MVSC++ 2010 Pro .New project -> C++ -> WIndow 32 console apllication -> Empty project .Then , i add file .CPP in solution and code
Can you demo in my code . Thank
The differences in Windows are:
1. gethostbyaddr() is implemented in the WinSock 2 library, so you'll need to initialise WinSock by calling WSAStartup. There's more info here, including an example.
http://msdn.microsoft.com/en-us/library/windows/desktop/ms742213%28v=vs.85%29.aspx

2. You'll need to add library ws2_32.lib to the link section of your project. Remember to add it both Debug and Release.

3. MSDN has an example of gethostbyaddr() on Windows. It's pretty much the same as on Unix.
http://msdn.microsoft.com/en-us/library/windows/desktop/ms738521%28v=vs.85%29.aspx
Hi kbw
I have link library string_sub of project . After read two link reference . I try it . I try convert String to char , but not convert , Can you see it .Thank
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <string>
#include <conio.h>
#include <stdio.h>
#include <WinSock2.h>  

#pragma comment(lib, "ws2_32") 

WSADATA wsaData; 
HOSTENT* list_ip;  
IN_ADDR addr; 

using namespace std;

string getip(string hostname) 
{
	WSAStartup(MAKEWORD(2,0),&wsaData);
	list_ip=gethostbyname((char)hostname); // convert string to char

	if (list_ip ==NULL)
	{
		ExitProcess(0);
	}
		
	memcpy(&addr.S_un.S_addr , list_ip->h_addr_list, list_ip->h_length);
	return inet_ntoa(addr);
	WSACleanup();
}

void main ()
{
    string string_main="http://abc-xyz.com/www/~av.50.22.100.250?url.aspx/etc";

	int count=0;

	string string_sub;
	ifstream infile;
	infile.open ("E:\\test.txt");

        while(!infile.eof()) // To get you all the lines.
        {
	        getline(infile,string_sub); // Saves the line in string_sub.
	       // cout<<string_sub<<"\n"; // Prints our string_sub.

			if (!string_sub.empty())
			{
				//size_t result = string_main.find( string_sub ); //check string_sub on the text file line by line, comparable to string_main

				//if( result != string::npos )  // if found
				//{
				//	count+=1;
				////	cout << "String is found at position"<< myfile.tellg() << "\n"; 
				//}
				string temp=getip(string_sub);
				cout << temp <<"\n";
			}
        }
	infile.close();
	//cout<< count <<"\n";
	if (count != 0)
	{
		cout << "Found\n";
	}
	else
	{
		cout << "Not found\n";
	}

getch();
}
You convert a string to a char like this hostname.c_str() but you need to pass a constant char pointer to the "gethostbyname()" function so reference the first character in the string like this &hostname[0]
Are you trying ip address from hostname or the hostname from ip address?

Only call WSAStartup once near the beginning of your program.

Why is this global?
 
HOSTENT* list_ip;
In general, you should resist the temptation to use global variables.

This:
 
list_ip=gethostbyname((char)hostname); // convert string to char 
should probably be:
 
list_ip = gethostbyname(hostname.c_str());

Also, this:
1
2
3
4
5
6
	ifstream infile;
	infile.open ("E:\\test.txt");

        while(!infile.eof()) // To get you all the lines.
        {
	        getline(infile,string_sub); // Saves the line in string_sub. 
should be:
1
2
3
	ifstream infile("E:\\test.txt");
        while (getline(infile, string_sub))
        {
Last edited on
Hi kbw , i so sory . I want to get IP Address from hostname
Can you test my code ? .
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <string>
#include <conio.h>
#include <stdio.h>
#include <WinSock2.h>  

#pragma comment(lib, "ws2_32") 

WSADATA wsaData; //golbal
//HOSTENT* list_ip;  golbal
IN_ADDR addr;  //golbal

using namespace std;

string getip(string hostname) 
{
	HOSTENT* list_ip; // not golbal, in this function
		/*
		// convert string to char 
		char c[1000];
		int so=hostname.size();
		for(int a=0;a<=so;a++)
		{
			c[a]=hostname[a];
		}
		*/
		WSAStartup(MAKEWORD(2,0),&wsaData);
		//list_ip=gethostbyname(c);

	list_ip=gethostbyname(hostname.c_str()); //convert hostname from string to char

	if (list_ip ==NULL)
	{
		ExitProcess(0);
	}
		
	memcpy(&addr.S_un.S_addr , list_ip->h_addr, list_ip->h_length);
	return inet_ntoa(addr);
	WSACleanup();
}

void main ()
{
    //string string_main="http://abc-xyz.com/www/~av.50.22.100.250?url.aspx/etc";

	//int count=0;

	string string_sub;

	ifstream infile("E:\\test.txt");

        while(!infile.eof()) // To get you all the lines.
        {
	        getline(infile,string_sub); // Saves the line in string_sub.
	        cout<<string_sub<<"\n"; // Prints our string_sub.
			
			if (!string_sub.empty()) //check line have content 
			{
				string temp=getip(string_sub); //temp get ip from string_sub
				cout <<temp<<"\n"; //prints IP of hostname

				//size_t result = string_main.find( string_sub ); //check string_sub on the text file line by line, comparable to string_main
			
				//if( result != string::npos )  // if found
				//{
				//	count+=1;
				//	//cout << "String is found at position"<< infile.tellg() << "\n"; 
				//}	
			}
        }
	infile.close();
	/*cout<< count <<"\n";
	if (count != 0)
	{
		cout << "Found\n";
	}
	else
	{
		cout << "Not found\n";
	}*/
getch();
}

But i can not get IP address ??? This is test.txt file
1
2
3
4
5
6
7
8
9
10
cplusplus.com

c++.com
C#.com

google.com



c+++.com

Thank you.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#ifdef _WIN32
	#include <WinSock2.h>
	#include <WS2tcpip.h>
	typedef unsigned uint32_t;
#else
	#include <netdb.h>
	#include <arpa/inet.h>
	#include <netinet/in.h>
	#include <sys/socket.h>  // BSD needs this
#endif

#include <iostream>
#include <string>
#include <stdexcept>

std::string getip(std::string hostname) 
{
	if (struct hostent* hent = gethostbyname(hostname.c_str()))
	{
		if (hent->h_addrtype == AF_INET  &&  hent->h_length == sizeof(uint32_t))
		{
			struct in_addr addr = { 0 };
			addr.s_addr = *(uint32_t*)hent->h_addr;
			return inet_ntoa(addr);
		}

		std::string text = "cannot find ip4 address for host:" + hostname;
		throw std::runtime_error(text);
	}

	std::string text = "cannot find ip address for host:" + hostname;
	throw std::runtime_error(text);
}

int main()
{
#ifdef _WIN32
	WSADATA wsadata = { 0 };
	WSAStartup(MAKEWORD(2, 2), &wsadata);
#endif

	std::string line;
	while (std::cin >> line)
	{
		try
		{
			std::cout << getip(line) << std::endl;
		}
		catch (const std::exception &e)
		{
			std::clog << e.what() << std::endl;
		}
	}

	return 0;
}
Last edited on
Dear kbw. i understand anything you do .I think it`s helpfull . But Have you try my code ?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <string>
#include <conio.h>
#include <stdio.h>
#include <WinSock2.h>  

#pragma comment(lib, "ws2_32") 

WSADATA wsaData; //golbal
//HOSTENT* list_ip;  golbal
IN_ADDR addr;  //golbal

using namespace std;

string getip(string hostname) 
{
	HOSTENT* list_ip; // not golbal, in this function
		/*
		// convert string to char 
		char c[1000];
		int so=hostname.size();
		for(int a=0;a<=so;a++)
		{
			c[a]=hostname[a];
		}
		*/
		if ( WSAStartup( MAKEWORD( 1 , 1 ) , &wsaData ) != 0 ) 
		{
				cout << "WSAStartup Failed.";
		}
		else
		{
			WSAStartup(MAKEWORD(2,0),&wsaData);
			//list_ip=gethostbyname(c);

			list_ip=gethostbyname(hostname.c_str()); //convert hostname from string to char

			if (list_ip ==NULL)
			{
				//ExitProcess(0);
				cout<<"Unable to resolve host.";
			}
			else
			{
				memcpy(&addr.S_un.S_addr , list_ip->h_addr, list_ip->h_length);
				return inet_ntoa(addr);
				WSACleanup();
			}
		}
}

int main ()
{
    //string string_main="http://abc-xyz.com/www/~av.50.22.100.250?url.aspx/etc";

	//int count=0;

	string string_sub;

	ifstream infile("E:\\test.txt");

	if (!infile)
	{
		cout << "Unable to open file\n";
        exit(1); // terminate with error
	}
    while(!infile.eof()) // To get you all the lines.
	{
	    getline(infile,string_sub); // Saves the line in string_sub.
	    cout<<string_sub<<"\n"; // Prints our string_sub.
			
		if (!string_sub.empty()) //check line have content 
		{
			string temp=getip(string_sub); //temp get ip from string_sub
			cout <<temp<<"\n"; //prints IP of hostname

			//size_t result = string_main.find( string_sub ); //check string_sub on the text file line by line, comparable to string_main
			
			//if( result != string::npos )  // if found
			//{
			//	count+=1;
			//	//cout << "String is found at position"<< infile.tellg() << "\n"; 
			//}	
		}
    }
	infile.close();
	/*cout<< count <<"\n";
	if (count != 0)
	{
		cout << "Found\n";
	}
	else
	{
		cout << "Not found\n";
	}*/
	return 0;
//getch();
}

it seems fine. But I think we need to loop in lines 46-50 to print all IP of a hostname
Can you see it and try . If you have any ideas please share me
Thank
Last edited on
Getting onto a Windows box is a real pain for me these days. Anyway, I've run your code as is and it works, but it's not pretty. The output is:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
cplusplus.com
50.22.100.250

c++.com
Unable to resolve host.
C#.com
Unable to resolve host.

google.com
173.194.41.132



c+++.com
Unable to resolve host.


Your getip() function:
1. calls WSAStartup() twice
2. shouldn't compile as not all paths return a value.
3. uses global variables.
4. calls WSACleanup(), which would interfere in a large program that used sockets.
oh yeah , according to what you say, we have modified the function getip
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
string getip(string hostname) 
{
	WSADATA wsaData;
	IN_ADDR addr; 
	HOSTENT* list_ip;
        //int i=0;
		if ( WSAStartup( MAKEWORD( 2 , 2 ) , &wsaData ) != 0 ) 
		{
				cout << "WSAStartup Failed.";
		}
		else
		{
			list_ip=gethostbyname(hostname.c_str()); //convert hostname from string to char
			if (list_ip ==NULL)
			{
				//ExitProcess(0);
				cout<<"Unable to resolve host.";
			}
			else
			{
 //                              while (list_ip->h_addr_list[i] != 0)
//				{
//					addr.S_un.S_addr=*(u_long *)list_ip->h_addr_list[i++];
//					return inet_ntoa(addr);
//				}
				memcpy(&addr.S_un.S_addr , list_ip->h_addr, list_ip->h_length);
				return inet_ntoa(addr);
				WSACleanup();
			}
		}
		WSACleanup();
}

Do you think the same is true ?
Moreover, to be able to print out IP from a hostname , example google.com have six IP, we need to loop in lines 32-42 . Do you think so ?
Last edited on
Hi kbw .

1. calls WSAStartup() twice
Can you detail about it ?

2. shouldn't compile as not all paths return a value.
I think at line 27

3. uses global variables.
Declare in function:
1
2
3
WSADATA wsaData;
	IN_ADDR addr; 
	HOSTENT* list_ip;


4. calls WSACleanup(), which would interfere in a large program that used sockets.
Call it at line 28 or 31
With regard to your post here: http://www.cplusplus.com/forum/windows/74966/#msg402760
1. WSAStartup is called in lines 29 and 35.
2. If gethostbyname() fails, or WSAStartup on line 29 fails you have undefined exits. I think the code shouldn't compile, but it does and returns an empty string.
3. You should make your variables as local as possible. What happens if something else uses your global variables in ways you don't expect now as your program gets larger? A real mess the answer.

I posted code for you to demonstrate, the single call to WSAStartup at the start of the program, use of local variables and error handling and how to use the core function you were having problems with, gethostbyname().

You asked about returning a list of ip addresses. I've modified my sample to return that list. I hope this helps.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#ifdef _WIN32
	#include <WinSock2.h>
	#include <WS2tcpip.h>
	typedef unsigned uint32_t;
#else
	#include <netdb.h>
	#include <arpa/inet.h>
	#include <netinet/in.h>
	#include <sys/socket.h>  // BSD needs this
#endif

#include <iostream>
#include <string>
#include <stdexcept>
#include <vector>

typedef std::vector<std::string> strings_t;

strings_t getip(std::string hostname) 
{
	if (struct hostent* hent = gethostbyname(hostname.c_str()))
	{
		if (hent->h_addrtype == AF_INET  &&  hent->h_length == sizeof(uint32_t))
		{
			strings_t hosts;

			for (int i = 0; hent->h_addr_list[i]; ++i)
			{
				struct in_addr addr = { 0 };
				addr.s_addr = *(uint32_t*)hent->h_addr_list[i];
				hosts.push_back(inet_ntoa(addr));
			}
			return hosts;
		}

		std::string text = "cannot find ip4 address for host:" + hostname;
		throw std::runtime_error(text);
	}

	std::string text = "cannot find ip address for host:" + hostname;
	throw std::runtime_error(text);
}

int main()
{
#ifdef _WIN32
	WSADATA wsadata = { 0 };
	WSAStartup(MAKEWORD(2, 2), &wsadata);
#endif

	std::string line;
	while (std::cin >> line)
	{
		try
		{
			strings_t hosts = getip(line);
			for (strings_t::const_iterator p = hosts.begin(); p != hosts.end(); ++p)
				std::cout << *p << std::endl;
		}
		catch (const std::exception &e)
		{
			std::clog << e.what() << std::endl;
		}
	}

	return 0;
}
Last edited on
ok thank kbw
You are great !.
Topic archived. No new replies allowed.