Thread: gethostbyname

  1. #1
    Registered User
    Join Date
    Apr 2006
    Posts
    4

    gethostbyname

    Ok Im stuck on this function (gethostbyname). Im on windows and have Dev-C++. Can someone show me an example?

  2. #2
    Registered User Tonto's Avatar
    Join Date
    Jun 2005
    Location
    New York
    Posts
    1,465
    Code:
    struct hostent * hostEnt;
    hostEnt = gethostbyname("www.google.com");
    hostent definition:

    Code:
    struct hostent {
            char    *h_name;        /* official name of host */
            char    **h_aliases;    /* alias list */
            int     h_addrtype;     /* host address type */
            int     h_length;       /* length of address */
            char    **h_addr_list;  /* list of addresses */
    }
    Last edited by Tonto; 04-27-2006 at 07:51 PM.

  3. #3
    Registered User
    Join Date
    Apr 2006
    Posts
    4
    Well, I tried it, and Im pretty sure Im doing it correct, but I get errors. So heres my code and Ill tell you my errors after.
    Code:
    #include<stdlib.h>
    
    main()
    {
          char *hostname;
          struct hostent * ip;
          printf("*** Hostname To IP Resolver ***\n\nHostname: ");
          scanf("%s",&hostname);
          ip = gethostbyname(hostname);
          printf("\n\nIP: %s",ip);
          system("pause>nul");
          return(0);
    }
    The error I get is " [Linker error] undefined reference to `gethostbyname@4' "
    By the way, Ive already tried the way you suggested, but I got this error, so I dont know....

  4. #4
    Registered User
    Join Date
    Mar 2005
    Location
    Mountaintop, Pa
    Posts
    1,058
    Can someone show me an example?
    Code:
    #pragma comment( lib, "ws2_32.lib" )
    #include <winsock.h>
    #include <stdio.h>
    
    int main(void)
    {
        WORD wVersionRequested; 
        WSADATA wsaData;
        SOCKADDR_IN SockAddr;
    
        wVersionRequested = MAKEWORD (1,1);
        if(WSAStartup(wVersionRequested , &wsaData) != 0)
        {
            printf("WSAStartup() Error! \n");
            return 1;
        }
        hostent* HostInfo = gethostbyname("www.google.com");
        memcpy(&(SockAddr.sin_addr),HostInfo->h_addr,HostInfo->h_length);
        char* pIP = inet_ntoa(SockAddr.sin_addr);
        printf("IP Address: %s\n", pIP);
        WSACleanup();
    return 0;
    }

  5. #5
    Registered User
    Join Date
    Mar 2005
    Location
    Juneda
    Posts
    291
    as BobS0327 wrotes on the 1st sample line: you should link with the winsock library. but on devcpp you should link from 'project -> options -> params -> linker', just browse till devcpp dir, go to 'lib' dir and select 'libws2_32' for winsock2. note that devcpp uses *.a libraries instead *.lib. hope that helps.

    niara

  6. #6
    Registered User
    Join Date
    Apr 2006
    Posts
    4
    ok well I made a new project and included that linker path, and it compiled, but the output IP says <null>. Below is my code.
    Code:
    #include<stdlib.h>
    #include<winsock.h>
    
    main()
    {
          while(1)
          {
          char *hostname;
          struct hostent * ip;
          system("cls");
          printf("*** Hostname To IP Resolver ***\n\nHostname: ");
          scanf("%s",&hostname);
          ip = gethostbyname(hostname);
          printf("\n\nIP: %s\n",ip);
          system("pause>nul");
          }
          return(0);
    }
    Bob , the following is the errors your code output after I made another new project and tried it.
    Code:
    Compiler: Default compiler
    Building Makefile: "C:\Documents and Settings\Owner\Desktop\Makefile.win"
    Executing  make...
    make.exe -f "C:\Documents and Settings\Owner\Desktop\Makefile.win" all
    gcc.exe -c main.c -o main.o -I"C:/Dev-Cpp/include"   
    
    main.c: In function `main':
    main.c:17: error: `hostent' undeclared (first use in this function)
    main.c:17: error: (Each undeclared identifier is reported only once
    main.c:17: error: for each function it appears in.)
    main.c:17: error: `HostInfo' undeclared (first use in this function)
    
    make.exe: *** [main.o] Error 1
    
    Execution terminated
    Last edited by TenFold; 04-29-2006 at 08:15 AM.

  7. #7
    Registered User
    Join Date
    Mar 2005
    Location
    Juneda
    Posts
    291
    bob's code works well for me in devcpp, and your code works well with the right synthax: take a look on the bob's code and see the diferences. see that first of all you should init the winsock through 'WSAStartup'. another thing, have you tryed to printf the 'hostname' char? it's really a host name in it before run the 'gethostbyname'? and finally to get the ip adress take another look to the bob's sample: he doesn't printf directly the 'hostent*' structure. take also a look at the tonto first post: 'hostent' is not a char, so you can't printf as a '%s' value.

    do not copy/paste, is easyer than it seems:
    Code:
    hostent* HostInfo;
    char hostname[1024];
    char *ip;
    WSADATA wsaData;
    SOCKADDR_IN SockAddr;
    
    if(WSAStartup(MAKEWORD(1,1),&wsaData)!=0) {return 0;}
    printf("*** Hostname To IP Resolver ***\n\n");
    while(1)
          {
          printf("HOSTNAME:\t");
          scanf("%s",&hostname);
          HostInfo=gethostbyname(hostname);
          memcpy(&(SockAddr.sin_addr),HostInfo->h_addr,HostInfo->h_length);
          ip=inet_ntoa(SockAddr.sin_addr);
          printf("IP:\t\t%s\n\n",ip);
          }    
    WSACleanup();
    return 0;
    you can see that there's anything not said int that thread

    niara
    Last edited by Niara; 04-29-2006 at 11:35 AM.

  8. #8
    Registered User
    Join Date
    Apr 2006
    Posts
    4
    ahh screw it, none of anyones code works. Ill just go with perl or php

  9. #9
    Registered User
    Join Date
    Mar 2005
    Location
    Mountaintop, Pa
    Posts
    1,058
    TenFold,

    PM me if want the whole Dev-Cpp project for this gethostbyname util. I will zip it and email it to you.

  10. #10
    Registered User OnionKnight's Avatar
    Join Date
    Jan 2005
    Posts
    555
    I have no luck with using gethostbyname() either. gethostbyname() won't do DNS resolves. For example if I give it "www.google.com" I get returned with NULL, if I were to feed it my own IP or "127.0.0.1" it works (but "localhost" doesn't). To make sure it's not just taking any shortcuts for IP-numbers I tried entering an erroneous IP, "123.123.123.123" and that returned NULL. Compilers used were Borland 5.6.1 and MinGW32 3.4.2 using both the winsock and winsock2 libraries.

    So gethostbyname() can't do hostnames? Is there some sort of conspiracy going on here, where only a select few get a working winsock lib?

  11. #11
    Registered User
    Join Date
    Mar 2005
    Location
    Mountaintop, Pa
    Posts
    1,058
    I'm not sure why gethostbyname isn't working for you. I've attached code that displays the last error with a textual description of that error. Maybe this can resolve the mystery.

    Code:
    #pragma comment( lib, "ws2_32.lib" )
    #include <winsock.h>
    #include <stdio.h>
    
    void printError( CHAR *msg )
    {
    	DWORD eNum;
    	CHAR sysMsg[256] = {0};
    	CHAR* p;
    
    	eNum = GetLastError( );
    	FormatMessage( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
    		NULL, eNum,
    		MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), 
    		sysMsg, 256, NULL );
    	p = sysMsg;
    	while( ( *p > 31 ) || ( *p == 9 ) )
    		++p;
    	do { *p-- = 0; } while( ( p >= sysMsg ) &&
    		( ( *p == '.' ) || ( *p < 33 ) ) );
    
    	printf( "ERROR: %s failed with error %d (%s)\n", msg, eNum, sysMsg );
    }
    
    int main(void)
    {
    	WORD wVersionRequested; 
    	WSADATA wsaData;
    	SOCKADDR_IN SockAddr;
    	hostent* HostInfo = NULL; 
    
    	wVersionRequested = MAKEWORD (1,1);
    	if(WSAStartup(wVersionRequested , &wsaData) != 0)
    	{
    		printError( "WSAStartup" );
    		return 1;
    	}
    	HostInfo = gethostbyname("www.google.com");
    	if (HostInfo == NULL)
    	{
    		printError("gethostbyname");
    	}
    	else
    	{ 
    		memcpy(&(SockAddr.sin_addr),HostInfo->h_addr,HostInfo->h_length);
    		CHAR* pIP = inet_ntoa(SockAddr.sin_addr);
    		printf("IP Address: %s\n", pIP);
    	}
    	WSACleanup();
    	return 0;
    }

  12. #12
    Registered User OnionKnight's Avatar
    Join Date
    Jan 2005
    Posts
    555
    For some reason my code works now. Sockets are mysterious.
    Code:
    #include <stdio.h>
    #include <winsock.h>
    
    int main (int argc, char** argv)
    {
    	struct sockaddr_in addr;
    	struct hostent* h;
    	char  buffer[BUFSIZ];
    	char* tmp;
    	WSADATA wsaData;
    
    	if (WSAStartup(MAKEWORD(1, 1), &wsaData)) {
    		fprintf(stderr, "Error: WSAStartup failed.\n");
    		return 1;
    	}
    	if (argc == 1) {
    		printf("host: ");
    		fgets(buffer, sizeof(buffer), stdin);
    		if ((tmp = strchr(buffer, '\n')) != NULL)
    			*tmp = '\0';
    		h = gethostbyname(buffer);
    	}
    	else {
    		h = gethostbyname(argv[1]);
    	}
    	if (h == NULL) {
    		//herror("Error: gethostbyname");
    		fprintf(stderr, "Error: gethosbyname() failed.\n");
    		WSACleanup();
    		return 1;
    	}
    	addr.sin_addr = *(struct in_addr*) h->h_addr;
    	printf("ip: %s", inet_ntoa(addr.sin_addr));
    
    	WSACleanup();
    	return 0;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. gethostbyname() won't work...
    By headbr in forum Networking/Device Communication
    Replies: 3
    Last Post: 08-14-2008, 06:51 AM
  2. GetHostByName
    By maxorator in forum C++ Programming
    Replies: 3
    Last Post: 11-04-2005, 02:08 PM
  3. gethostbyname allways NULL
    By BianConiglio in forum Windows Programming
    Replies: 6
    Last Post: 08-18-2005, 01:27 AM
  4. Replies: 1
    Last Post: 09-11-2004, 08:52 AM
  5. WinSock and gethostbyname() won't return correctly...
    By SyntaxBubble in forum C++ Programming
    Replies: 2
    Last Post: 07-05-2002, 12:08 PM