python中原始套接字的网络接口?

2024-10-01 09:30:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用Python为一个无线网桥编写一个小的配置实用程序,使用Ethernet II proto0x8888的原始套接字。有一些关于python原始套接字的教程,但是它们似乎都是硬编码网络接口(“eth0”、“eth1”等等),我不想这样做,因为每台计算机可能有不同的网络接口(在我的笔记本电脑上是“wlan0”)。在

用“我的当前代码”进行了“不幸的”编码:

# Create an Ethernet II broadcast of ethertype 0x8888:
s = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, 0x8888)
s.bind(("wlan0",0x8888))
ifName,ifProto,pktType,hwType,hwAddr = s.getsockname()
txFrame = struct.pack("!6s6sH","\xFF\xFF\xFF\xFF\xFF\xFF",hwAddr,0x8888) + "\x00"*0x32
# Send and wait for response
s.send(txFrame)

有没有办法在当前系统上获取网络接口名称,而不必硬编码?在

我试过了,但也没用。在


Tags: 实用程序编码教程socketeth1网络接口iixff
1条回答
网友
1楼 · 发布于 2024-10-01 09:30:15

您可以使用subprocess和re来获取网络接口的列表:

import subprocess, re

config = subprocess.check_output("ifconfig")
expr = re.compile("([a-zA-Z0-9]+)\s+Link")
interfaces = expr.findall(config)

ifconfig还提供了一些选项,允许您查看“down”接口,尽管我认为如果您想要广播,您不需要它们。有关详细信息,请参见man ifconfig。在

相关问题 更多 >