Winsock Functions


gethostbyname Function

The gethostbyname function retrieves host information corresponding to a host name from a host database.

Note  The gethostbyname function has been deprecated by the introduction of the getaddrinfo function. Developers creating Windows Sockets 2 applications are urged to use the getaddrinfo function instead of gethostbyname.

Syntax

C++
struct hostent* FAR gethostbyname(
  __in  const char *name
);

Parameters

name [in]

A pointer to the null-terminated name of the host to resolve.

Return Value

If no error occurs, gethostbyname returns a pointer to the hostent structure described above. Otherwise, it returns a null pointer and a specific error number can be retrieved by calling WSAGetLastError.

Error codeMeaning
WSANOTINITIALISED

A successful WSAStartup call must occur before using this function.

WSAENETDOWN

The network subsystem has failed.

WSAHOST_NOT_FOUND

Authoritative answer host not found.

WSATRY_AGAIN

Nonauthoritative host not found, or server failure.

WSANO_RECOVERY

A nonrecoverable error occurred.

WSANO_DATA

Valid name, no data record of requested type.

WSAEINPROGRESS

A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function.

WSAEFAULT

The name parameter is not a valid part of the user address space.

WSAEINTR

A blocking Windows Socket 1.1 call was canceled through WSACancelBlockingCall.

 

Remarks

The gethostbyname function returns a pointer to a hostent structure—a structure allocated by Windows Sockets. The hostent structure contains the results of a successful search for the host specified in the name parameter.

The memory for the hostent structure returned by the gethostbyname function is allocated internally by the Winsock DLL from thread local storage. Only a single hostent structure is allocated and used, no matter how many times the gethostbyaddr or gethostbyname functions are called on the thread. The returned hostent structure must be copied to an application buffer if additional calls are to be made to the gethostbyname or gethostbyaddr functions on the same thread. Otherwise, the return value will be overwritten by subsequent gethostbyname or gethostbyaddr calls on the same thread. The internal memory allocated for the returned hostent structure is released by the Winsock DLL when the thread exits.

An application should not try to release the memory used by the returned hostent structure. The application must never attempt to modify this structure or to free any of its components. Furthermore, only one copy of this structure is allocated per thread, so the application should copy any information it needs before issuing any other function calls to gethostbyname or gethostbyaddr .

The gethostbyname function cannot resolve IP address strings passed to it. Such a request is treated exactly as if an unknown host name were passed. Use inet_addr to convert an IP address string to an actual IP address, then use another function, gethostbyaddr, to obtain the contents of the hostent structure.

If the name parameter points to an empty string or name is NULL, the returned string is the same as the string returned by a successful gethostname function call (the standard host name for the local computer).

Note  The gethostbyname function does not check the size of the name parameter before passing the buffer. With an improperly sized name parameter, heap corruption can occur.

Example Code

The following examples demonstrates the use of the gethostbyname function.

#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>
#include <windows.h>
#pragma comment(lib, "wininet.lib")

int main(int argc, char **argv)
{

    //-----------------------------------------
    // Declare and initialize variables
    WSADATA wsaData;
    int iResult;

    DWORD dwError;
    int i = 0;

    struct hostent *remoteHost;
    char *host_name;
    struct in_addr addr;

    char **pAlias;

    // Validate the parameters
    if (argc != 2) {
        printf("usage: %s ipv4address\n", argv[0]);
        printf(" or\n");
        printf("       %s hostname\n", argv[0]);
        printf("  to return the host\n");
        printf("       %s 127.0.0.1\n", argv[0]);
        printf("  to return the IP addresses for a host\n");
        printf("       %s www.contoso.com\n", argv[0]);
        return 1;
    }
    // Initialize Winsock
    iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
    if (iResult != 0) {
        printf("WSAStartup failed: %d\n", iResult);
        return 1;
    }

    host_name = argv[1];

// 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 */
        printf("Calling gethostbyname with %s\n", host_name);
        remoteHost = gethostbyname(host_name);
    } else {
        printf("Calling gethostbyaddr with %s\n", host_name);
        addr.s_addr = inet_addr(host_name);
        if (addr.s_addr == INADDR_NONE) {
            printf("The IPv4 address entered must be a legal address\n");
            return 1;
        } else
            remoteHost = gethostbyaddr((char *) &addr, 4, AF_INET);
    }

    if (remoteHost == NULL) {
        dwError = WSAGetLastError();
        if (dwError != 0) {
            if (dwError == WSAHOST_NOT_FOUND) {
                printf("Host not found\n");
                return 1;
            } else if (dwError == WSANO_DATA) {
                printf("No data record found\n");
                return 1;
            } else {
                printf("Function failed with error: %ld\n", dwError);
                return 1;
            }
        }
    } else {
        printf("Function returned:\n");
        printf("\tOfficial name: %s\n", remoteHost->h_name);
        for (pAlias = remoteHost->h_aliases; *pAlias != 0; pAlias++) {
            printf("\tAlternate name #%d: %s\n", ++i, *pAlias);
        }
        printf("\tAddress type: ");
        switch (remoteHost->h_addrtype) {
        case AF_INET:
            printf("AF_INET\n");
            break;
        case AF_INET6:
            printf("AF_INET6\n");
            break;
        case AF_NETBIOS:
            printf("AF_NETBIOS\n");
            break;
        default:
            printf(" %d\n", remoteHost->h_addrtype);
            break;
        }
        printf("\tAddress length: %d\n", remoteHost->h_length);

        i = 0;
        while (remoteHost->h_addr_list[i] != 0) {
            addr.s_addr = *(u_long *) remoteHost->h_addr_list[i++];
            printf("\tIP Address #%d: %s\n", i, inet_ntoa(addr));
        }
    }

    return 0;
}

Requirements

Minimum supported clientWindows 2000 Professional
Minimum supported serverWindows 2000 Server
HeaderWinsock2.h
LibraryWs2_32.lib
DLLWs2_32.dll

See Also

Winsock Reference
Winsock Functions
getaddrinfo
gethostbyaddr
gethostname
WSAAsyncGetHostByName
hostent

Send comments about this topic to Microsoft

Build date: 11/12/2009

Tags :


Community Content

ddaS-edEn
Sending an empty string to gethostbyname()?

If the parameter passed to the gethostbyname() function is an empty string like:

 HOSTENT *pEnt = gethostbyname("");


the function returns a pointer to a HOSTENT object with the host name of the local host computer assigned into the h_name parameter.

Tags :

hoegaarden
small bug in example code
        case AF_INET6:
printf("AF_INET\n");

should be:
printf("AF_INET6\n");

Tags :

Thomas Lee
RPC server is too busy? why?
I'm working on a program has a self-upgrade feature, so it periodically calls a function that connects to a web server and sends a requests to check for a newer version. I'm using Visual Studio 2005 as my development platform. The program works fine and does what it is suppoed to do, however sometimes VS shows me a message that says: "First-chance exception at 0x766afbae in myprogram.exe: 0x000006BB: RPC server too busy to complete this operation." and execution breaks at the following statment:

hs = gethostbyname(host);


The message window has three buttons: "Break", "Continue" and "Ignore", if I choose "Continue" the execution continues for hours without problems. If I choose "Break" and then hit F5, VS ask me if I wish to ignore the buggy code, if I respond "Yes" the program continues runing properly for hours and hours, but if I asnwer "No" it shows another message that says: "First-chance exception at 0x774240eb in myprogram.exe: 0xC0000005: Access violation writing location 0x00000000." and execution cannot be resumed any more.

The wierd thing is that this problem always seem to occur shortly after I close IE7 or other web browser I was using to read my yahoo mail, or when click a navigation button inside yahoo mail.

Addtional information:

1.- The upgrade code creates a thread that does all the network operations (connect, request and download) and then exits.

2.- If I don't open up a web browser the program can work for days without any interruption.

3.- My OS is Windows Vista home basic.


I would like to know if anyone is having a similar problem, and apreciate very much a solution.
Thanks in advance.

UPDATE:

I modified my program to use geraddrinfo instead of gethostbyname and still have the same problem, but now the execption is dected somewhere inside ws2_32.dll. Once again, the problem pops up while navigating inside yahoo mail, but also while accessing msdn.

This is too crazy, if my code has a bug, then why this bug only shows up while I'm doing something with the web browser?, why no execption occurs as long as there's no web browser open?, and why the program continues working fine if I choose to ignore the exception?.

Hope someone can give me some light becuase this problem is driving me nuts.

Here is the call stack:

rpcrt4.dll!774240eb()
[Frames below may be incorrect and/or missing, no symbols loaded for rpcrt4.dll]
rpcrt4.dll!774240c3()
rpcrt4.dll!774aed87()
rpcrt4.dll!7746ca00()
ntdll.dll!77842119()
ntdll.dll!7780ba51()
ntdll.dll!777d0a5f()
ntdll.dll!777d0a64()
ntdll.dll!777f4fe0()
ntdll.dll!777d0a64()
advapi32.dll!762e7648()
advapi32.dll!762e7655()
advapi32.dll!762e7b7b()
ntdll.dll!777f43c0()
kernel32.dll!766bb637()
kernel32.dll!766bb651()
kernel32.dll!766b4516()
ntdll.dll!777f4810()
nsi.dll!779714b9()
ntdll.dll!777f4320()
kernel32.dll!766baeb6()
nsi.dll!779714ce()
nsi.dll!77971623()
nsi.dll!779716a0()
dnsapi.dll!75e15eb8()
dnsapi.dll!75e15620()
ntdll.dll!777f6e0c()
dnsapi.dll!75e15460()
dnsapi.dll!75e15f9e()
mswsock.dll!75664703()
mswsock.dll!75664668()
mswsock.dll!756644c2()
ntdll.dll!777f71e6()
ntdll.dll!778418bc()
ntdll.dll!77842869()
ntdll.dll!7784284d()
ntdll.dll!7784284d()
ntdll.dll!7780b7cd()
ntdll.dll!777f7512()
mswsock.dll!7566433d()
mswsock.dll!75664a2a()
mswsock.dll!75664a5c()
nlaapi.dll!74ed58cf()
nlaapi.dll!74ed58de()
NapiNSP.dll!71da1391()
winrnr.dll!71d91244()
ntdll.dll!777f7512()
ntdll.dll!777f7545()
kernel32.dll!766b9a26()
ws2_32.dll!766430e6()
ws2_32.dll!766456c5()
ws2_32.dll!76644732()
ws2_32.dll!76644712()
ws2_32.dll!76644654()
ws2_32.dll!766445c7()
ws2_32.dll!76645504()

[tfl - 05 09 09] Hi - and thanks for your post. You should post questions like this to the MSDN Forums at http://forums.microsoft.com/msdn or the MSDN Newsgroups at

http://www.microsoft.com/communities/newsgroups/en-us/. You are much more likely get a quicker response using the forums than through the Community Content. For specific help about:
Visual Studio :
http://groups.google.com/groups/dir?sel=usenet%3Dmicrosoft.public.vstudio%2C&
SQL Server :
http://groups.google.com/groups/dir?sel=usenet%3Dmicrosoft.public.sqlserver%2C&
.NET Framework :
http://groups.google.com/groups/dir?sel=usenet%3Dmicrosoft.public.dotnet.framework
PowerShell : http://groups.google.com/group/microsoft.public.windows.powershell/topics?pli=1
All Public : http://groups.google.com/groups/dir?sel=usenet%3Dmicrosoft.public%2C&


Page view tracker