Determine socket family at runtime

Francesco Bochicchio bockman at virgilio.it
Sun May 4 13:18:42 EDT 2008


On Sun, 04 May 2008 08:49:55 -0700, Giampaolo Rodola' wrote:

> Hi there,
> since the socket.socket.family attribute has been introduced only in
> Python 2.5 and I need to have my application to be backward compatible
> with Python 2.3 and 2.4 I'd like to know how could I determine the
> family of a socket.socket instance which may be AF_INET or AF_INET6.
> Is there some kind of getsockopt() directive I could use?
> For now I've been able to determine the family by using:
> 
> # self.socket = a connected socket.socket instance
> ip, port = self.socket.getsockname()[0:2]
> af = socket.getaddrinfo(ip, port)[0][0]
> 
> ...but I'd like to know if some other solution is preferable.
> 
> 
> 
> Thanks.
> 
> 
> --- Giampaolo
> http://code.google.com/p/pyftpdlib

Ciao,

what about wrapping the socket type and  adding a 'family' attribute
to the base socket class? Something like:

class SocketWrapper(socket.socket):
	def __init__(self, family, type, proto=0):
		socket.socket.__init__(self, family, type, proto)
		self.family = family

then you have just to create the sockets with SocketWrapper insetead of
socket.socket. For the rest of your code it would not matter, and then you 
are sure to always have a .family attribute.

Ciao
----
FB



More information about the Python-list mailing list