CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 13 of 13
  1. #1
    Join Date
    Feb 2013
    Posts
    30

    gethostbyaddr and gethostbyname

    Any help on this appreciated.

    This is a winsock program designed to prompt the user to enter a domain name.
    The program is then supposed to return to the user a resolved ip address of that domain name. The user should also be able to enter an IP address and receive back a domain name.

    While the program prompts the user to enter the domain name, all that is ever returned is error#:0

    Can anyone shed light on why??
    See code

    HTML Code:
    // Declare and initialize variables
    #include <winsock2.h>
    #include <ws2tcpip.h>
    #include <stdio.h>
    #include <windows.h>
    #pragma comment(lib, "ws2_32.lib")
    #include <iostream>
    
    int main(int argc, char **argv)
    {
    	hostent* remoteHost;
    		char* host_name;	
    		unsigned int addr;
    //------------------------------------------------------------------------------------------------
    		//Initialize WINSOCK 2
    		WSADATA wsaData; //structure that holds information about current wsock version.
    		if(WSAStartup(MAKEWORD(2,2), &wsaData) != 0) //start wsock version 2.2. Function returns
    		//0 if successful, otherwise, there was an error that needs to be reported.
    		{
    		std::cout << "WSAStartup failed: " << WSAGetLastError(); //report the error if there is one
    		return 1; //exit the program. 
    		}
    //-------------------------------------------------------------------------------------------------		
    		// User inputs name of host
    		printf("Input name of host: ");
    //-------------------------------------------------------------------------------------------------
    		// Allocate 64 byte char string for host name
    		host_name = (char*) malloc(sizeof(char)*64);
    		fgets(host_name, 64, stdin);
    //-------------------------------------------------------------------------------------------------
    		// If the user input is an alpha name for the host, use gethostbyname()
    		// If not, get host by addr (assume IPv4)
    		if (isalpha(host_name[0])) {   /* host address is a name */
    		// if hostname terminated with newline '\n', remove and zero-terminate 
    			if (host_name[strlen(host_name)-1] == '\n') 
    			host_name[strlen(host_name)-1] = '\0';
    			remoteHost = gethostbyname(host_name);
    			}
    			else  { 
    			addr = inet_addr(host_name);
    			remoteHost = gethostbyaddr((char *)&addr, 4, AF_INET);
    			}
    
    			if (WSAGetLastError() != 0) {
    				if (WSAGetLastError() == 11001)
    				printf("Host not found...\nExiting.\n");
    			}
    			else
    			printf("error#:%ld\n", WSAGetLastError());
    
    }

  2. #2
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,822

    Re: gethostbyaddr and gethostbyname

    The final else clause matches the if (WSAGetLastError() !=0) test, so if there are no errors the final printf is executed!

    Try something like this

    Code:
    	if (WSAGetLastError() != 0) {
    		if (WSAGetLastError() == 11001)
    			printf("Host not found...\nExiting.\n");
    		 else 
    			printf("error#:%ld\n", WSAGetLastError());
    		
    		return (2);
    	}
    
    	printf("Remote host name: %s\n", remoteHost->h_name);

  3. #3
    Join Date
    Feb 2013
    Posts
    30

    Re: gethostbyaddr and gethostbyname

    You are correct.
    That fixed it. Now it outputs information.
    However, the information is NOT the ip address like I thought.

    I want the user to input a domain name, like www.google.com
    and have the program resolve the DNS entry (via gethostby.... function) and output: 173.194.75.104

    Instead, it just kind of echoes what the user entered. See below:

    Input name of Host: www.google.com
    Remote host name: www.google.com


    Do I need to add another "else" condition?

  4. #4
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,822

    Re: gethostbyaddr and gethostbyname

    RemoteHost contains this information - look at the MSDN documentation for hostent.

    If you want to display the IP addresses then just use

    Code:
    for (int i = 0; char *a = remoteHost->h_addr_list[i]; i++)
    	printf("%i.%i.%i.%i\n", a[0], a[1], a[2], a[3]);

  5. #5
    Join Date
    Feb 2013
    Posts
    30

    Re: gethostbyaddr and gethostbyname

    Thanks very much.
    This does, indeed, produce the corresponding ip address, however, the ip is being displayed as:

    64.-254. -42.230 (just an example, note the hyphens.)

    Every domain name I enter, displays an ip address with these strange hyphens.
    Can you tell me why?

  6. #6
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,822

    Re: gethostbyaddr and gethostbyname

    Sorry. Change all the %i in the printf to %u. Printf is treating the numbers as signed so printing some as negative. They are unsigned numbers. I only gave an example of how to extract the ip address from the returned data.

  7. #7
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,822

    Re: gethostbyaddr and gethostbyname

    Surely not every domain name? When I try www.google.com I get

    173.194.67.104
    173.194.67.106
    173.194.67.99
    173.194.67.105
    173.194.67.103
    173.194.67.147

  8. #8
    Join Date
    Feb 2013
    Posts
    30

    Re: gethostbyaddr and gethostbyname

    Okay, I did it now it prints the following:

    When I entered www.yahoo.com the result is this:

    98.4294967179.4294967223.24

    Is the %u a different format all together?

  9. #9
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,822

    Re: gethostbyaddr and gethostbyname

    OK. In my build properties for the program I have char as default unsigned. You have it as signed. Thats the difference.

    Use
    Code:
    for (int i = 0; unsigned char *a = (unsigned char*)remoteHost->h_addr_list[i]; i++)
        printf("%i.%i.%i.%i\n", a[0], a[1], a[2], a[3]);

  10. #10
    Join Date
    Feb 2013
    Posts
    30

    Re: gethostbyaddr and gethostbyname

    You are the man!
    That worked. And it helps tremendously to understand the how and why.....

    Can I trouble you to get the program to do the opposite??
    So I'd then like to enter the ip address: 98.139.183.24 and get the result of www.yahoo.com

    I thought that the program that I'd submitted you, performed an "if, then" that would automatically see what you entered and resolve it accordingly.

  11. #11
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,822

    Re: gethostbyaddr and gethostbyname

    Er.. NO! Thats not how things work unfortunately. If you enter ip address 98.139.183.24 and get ir2.fp.vip.bf1.yahoo.com then your program is working! Try this. At the command line type nslookup and at the > prompt type www.yahoo.com. Then at the next > prompt type in the address just shown. Type exit to exit the program. Going from an ip address to a domain name is called reverse DNS lookup. To understand what is going on look at

    http://en.wikipedia.org/wiki/Reverse_DNS_lookup

    But the answer you get back is whatever has been designated for the in-addr.arpa address! What you are expecting is what is known as forward-confirmed reverse DNS. Some sites do and some don't!

    Try these

    www.nationwide.co.uk

    155.131.127.81

  12. #12
    Join Date
    Feb 2013
    Posts
    30

    Re: gethostbyaddr and gethostbyname

    So I have new code here that I need to do the same with.

    1. using the gethostbyname function, prompt user for domain name, which will be entered as a string to be resolved
    2. return the ip address of the domain entered.
    3. use inet_ntoa to format and display the ip address
    4. if an error is returned, print a message for the error using the WSAGetLastError

    HTML Code:
    // C++ DNS Processing (C++ Windows Version)
    #include <iostream>
    using namespace std;
    
    #include <winsock.h>
    
    int main(int argc, char **argv)
    {
         
         // Add the WSAStartup code...
         // Winsock 1.1
         WORD wVersionRequested = MAKEWORD(1,1);
         WSADATA wsaData;
    
         // Define the structure for the returned data
         struct hostent *hostptr;
    
         // Test case... change to other names or define in input variable
         char *exampleHostName = "www.sunybroome.edu";
    
         // Return code for the Winsock network startup
         int nRet;
    
         // Initialize the Winsock environment
         nRet = WSAStartup(wVersionRequested, &wsaData);
    
         // Check to make sure the environment initialized successfully
         if(wsaData.wVersion != wVersionRequested)
         {
              cout << "Wrong version\n";
              return 0;
         }
    
         if (hostptr = gethostbyname (exampleHostName) )
         {
              //
              // The IP address is now in hostptr->h_addr
              // Print out the contents of hostent structure
              // in an easily readable form with labels. For
              // example, the host name can be output using:
    
              cout << "Host name: " << hostptr->h_name << endl;
         }
         else
         {
              // An error has occurred. Display an informative
              // error message using the result of WSAGetLastError()
         }
    }

  13. #13
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,822

    Re: gethostbyaddr and gethostbyname

    This will display the ip address(s) the way you want it

    Code:
    	cout << "Host Name: " << hostptr->h_name << endl;
    
    	cout << "IP address(s)" << endl;
    	for (int i = 0;  struct in_addr *a = (struct in_addr*)hostptr->h_addr_list[i]; i++)
                cout << inet_ntoa(*a) << endl;
    This will display an error message

    Code:
    	if (WSAGetLastError() == 11001)
    		cout << "Host not found" << endl;
    	else
    		cout << "error#: " << WSAGetLastError() << endl;

Posting Permissions

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





Click Here to Expand Forum to Full Width

Featured