Link to home
Start Free TrialLog in
Avatar of pluim
pluim

asked on

Lookup IP address from hostname (C/socket)

How do I find the IP address for a given host, in C?
This is on a UNIX box (AIX), TCP/IP installed and
DNS available. Assume a hostname has no aliases and
only one associated IP address.

This is the code I have so far:

  struct hostent      *host;
  struct sockaddr_in  sa;
  char                ipaddress[32];

  host=gethostbyname("someserver.com");

  ... get IP address ...

  memset (&sa, '\0', sizeof(sa));
  sa.sin_family      = AF_INET;
  sa.sin_addr.s_addr=inet_addr(ipaddress);
  sa.sin_port        = 80;          

Thanks,
pluim.
Avatar of msmanju
msmanju

try this

sa.sin_addr.s_addr= *((unsigned long *)host->h_addr);
Avatar of pluim

ASKER

msmanju, thanks for the answer. However, as I hoped the code would explain, I want the IP address in a readable format (hence the char ipaddress[32]).
Something in the form "1.2.3.4".

Thanks.

ASKER CERTIFIED SOLUTION
Avatar of alextr
alextr
Flag of Italy image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial