How to use getnameinfo instead of gethostbyname?

cnd picture cnd · Apr 27, 2012 · Viewed 26.9k times · Source

in code :

if ((host = (struct hostent*) gethostbyname(address) ) == 0) // address is a string

I've got warning when cross compiling (generic arm architecture) on 4.5.x gcc :

(.text+0x1558): warning: gethostbyname is obsolescent, use getnameinfo() instead.

getnameinfo is:

int WSAAPI getnameinfo(
  __in   const struct sockaddr FAR *sa,
  __in   socklen_t salen,
  __out  char FAR *host,
  __in   DWORD hostlen,
  __out  char FAR *serv,
  __in   DWORD servlen,
  __in   int flags
);

And it got more parameters... And I'm confused with it, I just need it work as gethostbyname were working. What parameter to pass to keep it simple stupid as it was with gethostbyname?

Finally here is my try:

struct sockaddr_in servAddr;
struct hostent *host;        /* Structure containing host information */

/* open socket */
if ((handle = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
    return LILI_ERROR;

memset(&servAddr, 0, sizeof(servAddr));
servAddr.sin_family      = AF_INET;
servAddr.sin_addr.s_addr = inet_addr(address.ptr());
servAddr.sin_port        = htons(port);

char servInfo[NI_MAXSERV];
if ( ( host = (hostent*) getnameinfo(
                 (struct sockaddr *) &servAddr
                 ,sizeof (struct sockaddr)
                 ,address.ptr(), address.size()
                 ,servInfo, NI_MAXSERV
                 ,NI_NUMERICHOST | NI_NUMERICSERV )  ) == 0)
    return LILI_ERROR;

if (::connect(handle, (struct sockaddr *) &servAddr, sizeof(servAddr)) < 0)
    return LILI_ERROR;

It compiles well and no segmentation fault on start up but I can't connect my server with it :(

Answer

Robert Siemer picture Robert Siemer · May 19, 2013

gethostbyname() does a name→IP lookup. It should be replaced with getaddrinfo(), which can do the same.

This means the warning is completely wrong. getnameinfo() is the replacement of gethostbyaddr(), both for IP→name lookups. The reverse.

name→IP: gethostbyname(), getaddrinfo()
IP→name: gethostbyaddr(), getnameinfo()

The newer functions can do more: they handle IPv6 and can translate strings like 'http' to 80 (port). In the future they can also determine if e.g. TCP should be used for the service in question or SCTP. The interface is ready.