5

我正在尝试连接/绑定到特定的网络接口卡 (NIC) 或无线网络接口。例如,当我创建一个套接字时,我想使用网络名称(例如“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,但没有任何效果。

非常感谢!!!

4

2 回答 2

2

其实答案很简单。它类似于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

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

谢谢您的帮助!

于 2013-12-04T18:34:31.700 回答
1

您需要libnl及其 python 绑定:

#!/usr/bin/env python

import netlink.core as netlink
import netlink.route.link as link
import netlink.route.address as Address

sock = netlink.Socket()
sock.connect(netlink.NETLINK_ROUTE)

cache = link.LinkCache()
cache.refill(sock)
intf = cache['wlan0']

addr_cache = Address.AddressCache()
addr_cache.refill()

for addr in addr_cache:
    if addr.ifindex == intf.ifindex:
        print addr
于 2013-11-09T23:26:01.850 回答