Get the ipv6 address from a interface

Roy Smith roy at
Thu Apr 9 14:17:29 CEST 2009

In article 
<86176ef7-c2e0-4c5d-b883-d91672e3eb0b at>,
 Kai Timmer <email at> wrote:

> Hello,
> i need a function that returns the ipv6 address from a given interface
> name. For ipv4 i use this one:
> def get_ip_address(ifname):
>   s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
>   return socket.inet_ntoa(fcntl.ioctl(
>       s.fileno(),
>       0x8915,  # SIOCGIFADDR
>       struct.pack('256s', ifname[:15])
>   )[20:24])
> which works great. But i am not enough into python to port that to
> ipv6. It has to work under linux only. Any help is appreciated.

I'm not 100% sure what you're trying to do, but the above is horribly 
non-portable.  You probably want to be looking at socket.getpeername() and 

In general, concepts like "the address of an interface" are difficult.  In 
many OS's, a given interface may have multiple addresses.  This is 
especially true in IPv6 where you've have both link local and global 
unicast addresses on the same interface.

Can you back up a few steps and describe what it is that you're trying to 
do, i.e. the use case?

More information about the Python-list mailing list