How to get ip from hostname and find it ?

EDN Admin

Well-known member
Joined
Aug 7, 2010
Messages
12,794
Location
In the Machine
Hello everybody !<br/>
<br/>
I have a small program C++ in Visual Studio 2010, its function is to find the IP address from hostname on the text file, compare with search string<br/>

<pre class="prettyprint #include <stdlib.h>
#include <iostream>
#include <fstream>
#include <string>
#include <conio.h>
#include <stdio.h>
#include <WinSock2.h>
#pragma comment(lib, "ws2_32")
using namespace std;

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)
{
//cout<<"Unable to resolve host.";
//ExitProcess(1);
}
else
{
/*while (list_ip->h_addr_list != 0)
{
addr.S_un.S_addr=*(u_long *)list_ip->h_addr_list[i++];
return (string)inet_ntoa(addr);
}*/
memcpy(&addr.S_un.S_addr , list_ip->h_addr, list_ip->h_length);
return inet_ntoa(addr);
WSACleanup();
}
}
//return inet_ntoa(addr);
//WSACleanup();
}

void main ()
{
// 74.125.71.100 one of six IP of google.com
string string_main="http://abc-xyz.com/www/~av.74.125.71.100?url.aspx/etc";
int count=0;
string string_sub;
ifstream infile("E:\test.txt");
if (!infile)
{
cout << "Unable to open filen";
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
if (!temp.empty())
{
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 << "Foundn";
}
else
{
cout << "Not foundn";
}
system("pause");
}[/code]
<br/>
Before , I have read this reference gethostbyname() at http://msdn.microsoft.com/en-us/library/windows/desktop/ms738524%28v=vs.85%29.aspx
http://msdn.microsoft.com/en-us/library/windows/desktop/ms738524%28v=vs.85%29.aspx . It can show six IP address of "google.com" . I noticed this place<br/>
<br/>

<pre class="prettyprint else
{
////......
i = 0;
if (remoteHost->h_addrtype == AF_INET)
{
while (remoteHost->h_addr_list != 0)
{
addr.s_addr = *(u_long *) remoteHost->h_addr_list[i++];
printf("tIP Address #%d: %sn", i, inet_ntoa(addr));
}
}
}[/code]
And this is result of my program. It`s only get one IP of hostname "google.com" .
<img alt="" src="http://social.msdn.microsoft.com/Forums/getfile/137655 <br/>
Can you tell me how to fix to be able to get a full IP from hostname . Thank you.

View the full article
 
Back
Top