How to get ip to hostname ?
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 14 of 14

Thread: How to get ip to hostname ?

  1. #1
    Join Date
    Jul 2012
    Posts
    25

    Question 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


    Code:
    codeguru.com
    
    c++.com
    C#.com
    
    google.com
    
    
    
    c+++.com

    And this is my code


    Code:
    #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.123.456.789.000?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 .

  2. #2
    Join Date
    Oct 2006
    Location
    Sweden
    Posts
    3,632

    Re: How to get ip to hostname ?

    Debugging is twice as hard as writing the code in the first place.
    Therefore, if you write the code as cleverly as possible, you are, by
    definition, not smart enough to debug it.
    - Brian W. Kernighan

    To enhance your chance's of getting an answer be sure to read
    http://www.codeguru.com/forum/announ...nouncementid=6
    and http://www.codeguru.com/forum/showthread.php?t=366302 before posting

    Refresh your memory on formatting tags here
    http://www.codeguru.com/forum/misc.php?do=bbcode

    Get your free MS compiler here
    http://www.microsoft.com/visualstudio/eng/downloads

  3. #3
    Join Date
    Jul 2012
    Posts
    25

    Re: How to get ip to hostname ?

    Hi S_M_A . I have read two topic at reference
    In this case . can you build function in my code above ? . If possible , thank so much
    Code:
    string getip(string hostname)
    {
    	//function get ip
    }
    In addition , i try code of "OneEyeMan"
    Code:
    #include "stdafx.h"
    #include <WinSock2.h>
    
    int _tmain(int argc, _TCHAR* argv[])
    {
    	WSADATA data;
    	struct hostent *host;
    	int result;
    	DWORD error;
    	result = WSAStartup( MAKEWORD( 2, 2 ), &data );
    	if( result )
    	{
    		printf( "Error initializing sockets!\n\r" );
    		return 1;
    	}
    	host = gethostbyname( "www.google.com" );
    	if( !host )
    	{
    		error = WSAGetLastError();
    	}
    	return 0;
    }
    And this is error
    Name:  46f3189ccb131b9d8c1167b211deee98_47085342.sshot1.png
Views: 217
Size:  33.7 KB
    Thank

  4. #4
    Join Date
    Oct 2006
    Location
    Sweden
    Posts
    3,632

    Re: How to get ip to hostname ?

    You obviously don't have a stdafx.h. How did you create the project and what MSVC version do you use?
    Debugging is twice as hard as writing the code in the first place.
    Therefore, if you write the code as cleverly as possible, you are, by
    definition, not smart enough to debug it.
    - Brian W. Kernighan

    To enhance your chance's of getting an answer be sure to read
    http://www.codeguru.com/forum/announ...nouncementid=6
    and http://www.codeguru.com/forum/showthread.php?t=366302 before posting

    Refresh your memory on formatting tags here
    http://www.codeguru.com/forum/misc.php?do=bbcode

    Get your free MS compiler here
    http://www.microsoft.com/visualstudio/eng/downloads

  5. #5
    Join Date
    Jul 2012
    Posts
    25

    Re: How to get ip to hostname ?

    Quote Originally Posted by S_M_A View Post
    You obviously don't have a stdafx.h. How did you create the project and what MSVC version do you use?
    MVSC 2010 Pro v10.0.30319
    I created project : New Project -> C++ ->WIn 32 console Aplication -> Empty Project . Then I add file .CPP to project.

  6. #6
    Ejaz's Avatar
    Ejaz is offline Elite Member Power Poster
    Join Date
    Jul 2002
    Location
    Lahore, Pakistan
    Posts
    4,211

    Re: How to get ip to hostname ?

    1. Don't use conio.h/stdio.h. use iostream, which is more C++ oriented.

    2. You have created an empty project, therefore there is no "stdafx.h" file, while copy/pasting the code, you've picked this one too, hence your compiler is complaining that it cannot find this file.

    3. You also need to link with "ws2_32.lib", otherwise you'll started getting linking errors once you are done with compiler errors.

    Following is the code for your reference.

    Code:
    #define WIN32_LEAN_AND_MEAN
    
    #include <iostream>
    #include <Windows.h>
    #include <tchar.h>
    #include <WinSock2.h>
    
    #pragma comment(lib, "ws2_32.lib")	// Need to link with ws2_32.lib
    
    int _tmain(int argc, _TCHAR* argv[])
    {
    	WSADATA data;
    	struct hostent *host;
    	int result;
    	DWORD error;
    
    	result = WSAStartup( MAKEWORD( 2, 2 ), &data );
    
    	if( result )
    	{
    		std::cout << "Error initializing sockets!" << std::endl;
    		return 1;
    	}
    
    	host = gethostbyname( "www.google.com" );
    
    	if( !host )
    	{
    		error = WSAGetLastError();
    	}
    	return 0;
    }

  7. #7
    Join Date
    Jul 2012
    Posts
    25

    Re: How to get ip to hostname ?

    Quote Originally Posted by Ejaz View Post
    1. Don't use conio.h/stdio.h. use iostream, which is more C++ oriented.

    2. You have created an empty project, therefore there is no "stdafx.h" file, while copy/pasting the code, you've picked this one too, hence your compiler is complaining that it cannot find this file.

    3. You also need to link with "ws2_32.lib", otherwise you'll started getting linking errors once you are done with compiler errors.

    Following is the code for your reference.

    Code:
    #define WIN32_LEAN_AND_MEAN
    
    #include <iostream>
    #include <Windows.h>
    #include <tchar.h>
    #include <WinSock2.h>
    
    #pragma comment(lib, "ws2_32.lib")	// Need to link with ws2_32.lib
    
    int _tmain(int argc, _TCHAR* argv[])
    {
    	WSADATA data;
    	struct hostent *host;
    	int result;
    	DWORD error;
    
    	result = WSAStartup( MAKEWORD( 2, 2 ), &data );
    
    	if( result )
    	{
    		std::cout << "Error initializing sockets!" << std::endl;
    		return 1;
    	}
    
    	host = gethostbyname( "www.google.com" );
    
    	if( !host )
    	{
    		error = WSAGetLastError();
    	}
    	return 0;
    }
    Hi Ejaz . i try it and i get many error . All of error in file "ws2def.h" 127 Error and 16 Warning
    Name:  4dcdac4ef58d33e9e0bc5ebfdf575a56_47112209.sshot1.png
Views: 198
Size:  36.9 KB

  8. #8
    Join Date
    Jul 2012
    Posts
    25

    Re: How to get ip to hostname ?

    Hi Ejaz . I think I have libaray ws2_32.lib link. I have links and build, no errors, but can not get the result of running the IP of google.com
    Name:  61c7d7265ca5f70cac50b93e95621557_47113164.sshot2.png
Views: 210
Size:  74.0 KB

  9. #9
    Ejaz's Avatar
    Ejaz is offline Elite Member Power Poster
    Join Date
    Jul 2002
    Location
    Lahore, Pakistan
    Posts
    4,211

    Re: How to get ip to hostname ?

    Your question was to resolve the errors, which are done. Please start separate thread for different problems (i.e. do no start multiple question in a single thread). Anyway, for this specific case, you need to do little more. Following code is for your reference.

    Code:
    #include <iostream>
    #include <string>
    #include <winsock2.h>
    
    #pragma comment(lib, "ws2_32.lib")	// Need to link with ws2_32.lib
    
    std::string get_ip( const std::string& hostname )
    {
    	hostent * host_info;
    	WSADATA wsa_data;
    	SOCKADDR_IN sock_addr;
    
    	if ( WSAStartup( MAKEWORD( 1 , 1 ) , &wsa_data ) != 0 ) 
    	{
    		throw std::exception("WSAStartup Failed.");
    	}
    
    	host_info = gethostbyname( hostname.c_str() );
    
    	if ( host_info == NULL ) 
    	{
    		throw std::exception("Unable to resolve host.");
    	}
    
    	memcpy( &( sock_addr.sin_addr ) , 
    			host_info->h_addr		, 
    			host_info->h_length );
    
    	std::string ip = inet_ntoa( sock_addr.sin_addr );
    
    	WSACleanup();
    
    	return ip;
    }
    
    int main()
    {
    	try
    	{
    		std::string url("www.google.com");
    		std::cout << "IP of " << url << " : " << get_ip( url ) << std::endl;
    	}
    	catch ( std::exception& e )
    	{
    		std::cout << e.what() << std::endl;
    	}
    }

  10. #10
    Join Date
    Jul 2012
    Posts
    25

    Re: How to get ip to hostname ?

    Hi Ejaz . can you see my code . I think www.google.com have six IP address as pic above
    Code:
    #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();
    			}
    		}
    }
    
    void main ()
    {
        //string string_main="http://abc-xyz.com/www/~av.64.71.33.95?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();
    }
    And this is test.txt file
    Code:
    msdn.com
    
    c++.com
    C#.com
    
    google.com
    
    
    
    c+++.com
    But I can get IP address form hostname ?
    Thank you so much if you try it .
    Last edited by headshot; July 12th, 2012 at 05:58 AM.

  11. #11
    Join Date
    Nov 2000
    Location
    Voronezh, Russia
    Posts
    5,960

    Re: How to get ip to hostname ?

    Sample attached.

    Code:
    E:\Temp\660>660.exe www.google.com
    HostName: www.l.google.com
    Alias[0]: www.google.com
     Host[0]: 173.194.32.50
     Host[1]: 173.194.32.49
     Host[2]: 173.194.32.52
     Host[3]: 173.194.32.51
     Host[4]: 173.194.32.48
    Attached Files Attached Files
    Best regards,
    Igor

  12. #12
    Join Date
    Jul 2012
    Posts
    25

    Re: How to get ip to hostname ?

    Hi . thank for your help
    if you do not mind can see through my code, you can modify it slightly so that IP can print out. I think my jaw getip missing anything. Urge you to check out . I think in GetIP function
    Code:
    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();
    }
    Last edited by headshot; July 13th, 2012 at 08:51 PM.

  13. #13
    Join Date
    Jul 2012
    Posts
    25

    Re: How to get ip to hostname ?

    Hi all
    I have already edit function getip . I think it`s ok , but get one IP from hostname

  14. #14
    Ejaz's Avatar
    Ejaz is offline Elite Member Power Poster
    Join Date
    Jul 2002
    Location
    Lahore, Pakistan
    Posts
    4,211

    Re: How to get ip to hostname ?

    Take a look at the sample attached here by Igor, step through it with the debugger and see how it works.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Azure Activities Information Page

Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center