Advertisements

In article
<>,
Kai Timmer <> 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
socket.getsockname().

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?

Advertisements

> 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
> socket.getsockname().

This only works if you are actually connected. I think he wants to find
out the local address without actually connecting.
> 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.

In Linux, you can only have one IPv4 address per interface (and you have
to use alias interfaces, such as eth0:0, to assign multiple addresses
to a physical link).

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

> In Linux, you can only have one IPv4 address per interface (and you
> have to use alias interfaces, such as eth0:0, to assign multiple
> addresses to a physical link).

that's actually not correct, use the "ip" tool (iproute2 package) to see
how easily you can have several addresses to a single interface.
ip addr add 1.1.1.1/24 dev eth0
ip addr add 2.2.2.1/24 dev eth0

the need for alias interfaces has been removed, a long time ago (AFAIK
even before the 2.4 kernel).

Share This Page

Welcome to The Coding Forums!

Welcome to the Coding Forums, the place to chat about anything related to programming and coding languages.

Please join our friendly community by clicking the button below - it only takes a few seconds and is totally free. You'll be able to ask questions about coding or chat with the community and help others.
Sign up now!