Thread: getting ip address : gethostbyname()

  1. #1
    Just kidding.... fnoyan's Avatar
    Join Date
    Jun 2003
    Location
    Still in the egg
    Posts
    275

    getting ip address : gethostbyname()

    Hi

    Why do we use a sockaddr_in structure in order to get the ip address of any host whose ip information is retrieved with gethostbyname() and why can't we use h_addr_list elements directly!

    For exmaple
    Code:
    // whis works
    struct hostent *h;
    struct sockaddr_in sa;
    h = gethostbyname(hostname);
    
    for (i=0; h->h_addr_list[i]; i++) {
          memcpy ( &sa.sin_addr.s_addr, he.h_addr_list[nAdapter],he.h_length);
          printf("Address: %s\n", inet_ntoa(sa.sin_addr)); 
       }
    
    // this fails!
    struct hostent *h;
    h = gethostbyname(hostname);
    
    for (i=0; h->h_addr_list[i]; i++) {
          printf("Address: %s\n", h->h_addr_list[i]); 
       }
    the array elements in h_addr_list are *char. So, whay cannot we directly use those value?

  2. #2
    Registered User SKeane's Avatar
    Join Date
    Sep 2006
    Location
    England
    Posts
    234
    h_addr_list is a pointer to an array of pointers to addresses. Before IPv6 came along, the array was an array of pointers to in_addr structures. After IPv6 (if implemented) it is an array of pointers to either in_addr or in6_addr structures. It's unfortunate that they are defined as "char *" pointers as that causes confusion. They are not strings, which is why your program fails.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Linux raw socket programming
    By cnb in forum Networking/Device Communication
    Replies: 17
    Last Post: 11-08-2010, 08:56 AM
  2. DX - CreateDevice - D3DERR_INVALIDCALL
    By Tonto in forum Game Programming
    Replies: 3
    Last Post: 12-01-2006, 07:17 PM
  3. Identify dynamic IP address of network device
    By BobS0327 in forum Tech Board
    Replies: 2
    Last Post: 02-21-2006, 01:49 PM
  4. Im so lost at . .
    By hermit in forum C Programming
    Replies: 18
    Last Post: 05-15-2002, 01:26 AM