6

Do you know how I could get one of the IPv6 adress of one of my interface in python2.6. I tried something with the socket module which lead me nowhere.

Thanks.

jaes
  • 103
  • 1
  • 6

5 Answers5

5

The netifaces module should do it.

import netifaces
addrs = netifaces.ifaddresses('eth0')
addrs[netifaces.AF_INET6][0]['addr']
al45tair
  • 4,405
  • 23
  • 30
Mark
  • 106,305
  • 20
  • 172
  • 230
  • Thanks a lot, sadly I want to stay very simple in this script which should run on a lot of different environment. So I was looking for something which wouldn't necessitate an easy_install. But still, it works great, thanks again. – jaes Aug 02 '10 at 15:18
0

You could just simply run 'ifconfig' with a subprocess.* call and parse the output.

jvdneste
  • 1,677
  • 1
  • 12
  • 14
  • I thought about that, and I have actually a ready (and long) command to get my Ipv6 well formated. But it really look ugly. It must exist a righter way to do this. – jaes Aug 02 '10 at 15:07
0

Something like this might work:

with open('/proc/net/if_inet6') as f:
    for line in f:
        ipv6, netlink_id, prefix_length, scope, flags, if_name = line.split()
        print(if_name, ipv6)

https://tldp.org/HOWTO/Linux+IPv6-HOWTO/ch11s04.html

(Or do it the hard way using netlink: https://stackoverflow.com/a/70701203 )

Collin Anderson
  • 14,787
  • 6
  • 68
  • 57
0

Here's a refactoring of the OP's answer into a single subprocess. I had to guess some things about the output format of ip.

output = subprocess.run(
    ['ip','addr','show','br0'],
    text=True, check=True, capture_output=True)
for line in output.stdout.splitlines() 
:
    if "inet6" in line:
        if "fe80" not in line:
            addr = line.split("inet6")[1].strip()
            addr = addr.split("/64")[0]
print(addr)

In general, simple search and string substitution operations are both easier and quicker to perform directly in Python. You want to avoid running more than a single subprocess if you can. (Better still if you can do everything natively in Python, of course.)

tripleee
  • 175,061
  • 34
  • 275
  • 318
-5

I'll surely go with this, it sould be working good, even if I find that really ugly.

step1 = Popen(['ip','addr','show','br0'],stdout=PIPE)
step2 = Popen(['grep','inet6'],stdout=PIPE,stdin=step1.stdout)
step3 = Popen(['sed','-e','/fe80/d','-e','s/ *inet6 *//g','-e','s/\/64.*$//g'],stdout=PIPE,stdin=step2.stdout)
step4 = Popen(['tail','-n1'],stdout=PIPE,stdin=step3.stdout)
step4.communicate()[0]

Thanks for the help again.

jaes
  • 103
  • 1
  • 6