简体   繁体   English

linux下如何获取接口的IPv6地址

[英]How to get the IPv6 address of an interface under linux

Do you know how I could get one of the IPv6 adress of one of my interface in python2.6.你知道我如何在 python2.6 中获得我的一个接口的 IPv6 地址之一。 I tried something with the socket module which lead me nowhere.我用插座模块尝试了一些东西,这让我无处可去。

Thanks.谢谢。

The netifaces module should do it. netifaces模块应该这样做。

import netifaces
addrs = netifaces.ifaddresses('eth0')
addrs[netifaces.AF_INET6][0]['addr']

您可以简单地使用 subprocess.* 调用运行“ifconfig”并解析输出。

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 https://tldp.org/HOWTO/Linux+IPv6-HOWTO/ch11s04.html

(Or do it the hard way using netlink: https://stackoverflow.com/a/70701203 ) (或者使用 netlink 以艰难的方式完成: https ://stackoverflow.com/a/70701203)

Here's a refactoring of the OP's answer into a single subprocess.这是将 OP 的答案重构为单个子流程。 I had to guess some things about the output format of ip .我不得不猜测一些关于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.通常,直接在 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.) (当然,如果您可以在 Python 中本地完成所有操作,那就更好了。)

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.再次感谢您的帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM