1

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

我当前的工作代码是(不幸的是硬编码的“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)

有什么方法可以在当前系统上获取网络接口名称,而不必对其进行硬编码?

我已经尝试过 INADDR_ANY,但这也不起作用。

4

1 回答 1

0

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

import subprocess, re

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

ifconfig 还具有允许您查看“关闭”接口的选项,尽管我认为如果您想广播则不需要它们。有关man ifconfig更多详细信息,请参阅。

于 2012-02-05T17:58:57.183 回答