gpt4 book ai didi

python - 使用python绑定(bind)/连接到网络接口(interface)卡

转载 作者:太空狗 更新时间:2023-10-30 01:22:42 24 4
gpt4 key购买 nike

我正在尝试连接/绑定(bind)到特定的网络接口(interface)卡 (NIC) 或无线网络接口(interface)。例如,当我创建一个套接字时,我想使用网络名称(例如“wlan0”或“eth0”)而不是使用 IP 地址进行连接。在 JAVA 中,我可以使用以下代码轻松完成此操作:

//Initializing command socket

//String networkCard = "wlan0"; //or could be "eth0", etc.

NetworkInterface nif = NetworkInterface.getByName(networkCard);

Enumeration<InetAddress> nifAddresses = nif.getInetAddresses();

// IP address of robot connected to NIC
SocketAddress sockaddr = new InetSocketAddress("192.168.1.100", 80);

sock = new Socket();

// bind to the specific NIC card which is connected to a specific robot

sock.bind(new InetSocketAddress(nifAddresses.nextElement(), 0));

sock.connect(sockaddr,10000);

我想将其翻译成 Python,但遇到了困难。有关如何执行此操作的任何建议?

我正在使用 sockopt 和 AF_CAN,但没有任何效果。

非常感谢!!!

最佳答案

其实答案很简单。它类似于 Idx 在上一个答案中所做的:

def findConnectedRobot():

'''
Finds which robots are connected to the computer and returns the
addresses of the NIC they are connected to
'''
robot_address = [] # stores NIC address
import netifaces
# get the list of availble NIC's
for card in netifaces.interfaces():
try:
# get all NIC addresses
temp = netifaces.ifaddresses(\
card)[netifaces.AF_INET][0]['addr']
temp2 = temp.split('.')
# see if address matches common address given to NIC when
# NIC is connected to a robot
if temp2[0] == '192' and int(temp2[3]) < 30:
print('appending address: ' + temp)
robot_address.append(temp)
except BaseException:
pass
return robot_address

在我获得“机器人地址”后,我就可以像普通套接字一样绑定(bind)/连接到它们。

感谢您的帮助!

关于python - 使用python绑定(bind)/连接到网络接口(interface)卡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19872052/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com