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

问题描述 投票:0回答:6

你知道我如何在 python2.6 中获取我的接口之一的 IPv6 地址之一吗?我尝试使用套接字模块进行一些操作,但没有任何结果。

谢谢。

python linux ipv6
6个回答
5
投票

netifaces模块应该可以做到这一点。

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

0
投票

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


0
投票

这样的东西可能会起作用:

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://stackoverflow.com/a/70701203


0
投票

这里将OP的答案重构为单个子流程。我不得不猜测一些关于

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 本地完成所有操作,那就更好了。)


0
投票

使用 psutil 回答:

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'

-5
投票

我一定会接受这个,它应该会很好用,即使我发现它真的很难看。

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]

再次感谢您的帮助。

© www.soinside.com 2019 - 2024. All rights reserved.