简体   繁体   English

使用python绑定/连接到网络接口卡

[英]bind/connect to network interface card using python

I am trying to connect/bind to a specific Network Interface Card (NIC) or wireless network interface. 我正在尝试连接/绑定到特定的网络接口卡(NIC)或无线网络接口。 For instance, when I create a socket, I want to connect using the name of the network (such as 'wlan0' or 'eth0') instead of using the IP address. 例如,当我创建套接字时,我想使用网络名称(例如'wlan0'或'eth0')进行连接,而不是使用IP地址。 In JAVA I can do this easily with the following code: 在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);

I want to translate this to Python, but I am having a hard time. 我想把它翻译成Python,但我很难过。 Any suggestions on how to do this? 有关如何做到这一点的任何建议?

I was using sockopt and the AF_CAN, but nothing is working. 我正在使用sockopt和AF_CAN,但没有任何工作。

Thank you very much!!! 非常感谢你!!!

Actually the answer is very simple. 实际上答案很简单。 And its similar to what Idx did in the previous answer: 它类似于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

After I get the "robot addresses" then I can just bind/connected to them like a normal socket. 在我得到“机器人地址”后,我可以像普通插座一样绑定/连接它们。

Thanks for the help! 谢谢您的帮助!

You need libnl and its python bindings: 你需要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

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

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