你知道如何在Python2.6中获取我其中一个接口的IPv6地址吗?我尝试使用套接字模块,但没有成功。谢谢。
使用netifaces模块即可。
import netifaces
addrs = netifaces.ifaddresses('eth0')
addrs[netifaces.AF_INET6][0]['addr']
可能会像这样运作:
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
(或者使用 netlink 的困难方法:https://dev59.com/CWAf5IYBdhLWcg3w3l2l#70701203)
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)
通常来说,简单的搜索和字符串替换操作在Python中直接执行既更容易又更快速。如果可以的话,你应该避免运行超过一个子进程。(当然,如果你能够完全使用Python本身实现所有功能,则最好不过。)
import psutil
import socket
def get_ipv6_address_from_nic(interface):
interface_addrs = psutil.net_if_addrs().get(interface) or []
for snicaddr in interface_addrs:
if snicaddr.family == socket.AF_INET6:
return snicaddr.address
例子:
>>> get_ipv6_address_from_nic("lo")
'::1'
我肯定会选择这个,它应该能够很好地工作,即使我发现它真的很丑陋。
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]
再次感谢您的帮助。