简体   繁体   English

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

[英]Network interface for raw sockets in python?

I'm writing a small configuration utility for a wireless bridge in Python, using raw sockets with Ethernet II proto 0x8888. 我正在用Python编写一个小的配置实用程序,用于Python的无线网桥,使用带有Ethernet II proto 0x8888的原始套接字。 There are several tutorials on raw sockets for python, but all of them seem to hardcode the network interface ("eth0", "eth1", etc.), which I don't want to, because each computer might have a different network interface (on my laptop its "wlan0"). 有一些关于python原始套接字的教程,但是它们似乎都对网络接口(“ eth0”,“ eth1”等)进行了硬编码,我不想这样做,因为每台计算机可能都有不同的网络接口(在我的笔记本电脑上为“ wlan0”)。

My current working code is (unfortunatly with hardcoded "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)

Is there any way to get the network interface name on the current system instead of having to hardcode it? 有什么方法可以在当前系统上获取网络接口名称,而不必对其进行硬编码?

I have tried INADDR_ANY, but that doesn't work either. 我已经尝试过INADDR_ANY,但这也不起作用。

You can use subprocess and re to get a list of the network interfaces: 您可以使用subprocess和re获得网络接口的列表:

import subprocess, re

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

ifconfig also has options that allow you to see 'down' interfaces although I don't think you'll need them if you want to broadcast. ifconfig还具有允许您查看“向下”界面的选项,尽管我认为如果要广播,则不需要它们。 See man ifconfig for more details. 有关更多详细信息,请参见man ifconfig

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

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