Decoding ctypes structures

I am trying to enlist ctypes support in python, and I can get some simple things, but when it comes to unpacking c-structures, I find that I am encountering some difficulties. I decided that for this I should play a little, and although I know that the standard socket library implements gethostbyname_ex(), I thought that I would try to implement it with ctypesand libc.gethostbyname().

I can execute libc.gethostbyname()quite easily:

#!/usr/bin/env python
from ctypes import *

cdll.LoadLibrary('libc.so.6')
libc = CDLL('libc.so.6')
he = libc.gethostbyname("www.google.com")

But it gives me a data structure hostent. I thought the best way to unpack this is to grab the c-structure and create a class that inherits from ctypes.Structure, and so I came up with this (I found the definition of hostentstruct in netdb.h):

class hostent(Structure):
    '''
    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 from name server. */
    }
    '''
    _fields_ = [("h_name", c_char_p), ("h_aliases", POINTER(c_char_p)),
                ("h_addrtype", c_int), ("h_length", c_int),
                ("h_addr_list", POINTER(c_char_p))]

, h_aliases h_addr_list, , , 0- -, , , NULL- ValueError :

>>> he = hostent(libc.gethostbyname("www.google.com"))
>>> pprint.pprint(he.h_addr_list)
<__main__.LP_c_char_p object at 0xb75dae84>
>>> print he.h_addr_list[0]
Traceback (most recent call last):
  File "/tmp/py2659JxK", line 24, in <module>
    print he.h_addr_list[0]
ValueError: NULL pointer access

.

+3
1

, gethostbyname:

>>> libc.gethostbyname.restype = POINTER(hostent)
>>> he = libc.gethostbyname("www.google.com")[0]
>>> he.h_aliases[0]
'www.google.com'

, h_addr_list POINTER(c_char_p), c_char_p . POINTER(POINTER(c_ubyte)) , he.h_addr_list[0][:4], IPv4.

+4

All Articles