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.
The netifaces module should do it.
import netifaces
addrs = netifaces.ifaddresses('eth0')
addrs[netifaces.AF_INET6][0]['addr']
You could just simply run 'ifconfig' with a subprocess.* call and parse the output.
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 )
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.)
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.