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:
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;
char **h_aliases;
int h_addrtype;
int h_length;
char **h_addr_list;
}
'''
_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
.