首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用python绑定/连接到网络接口卡

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

Stack Overflow用户
提问于 2013-11-09 03:30:54
回答 2查看 4.1K关注 0票数 5

我试图连接/绑定到特定的网络接口卡(NIC)或无线网络接口。例如,在创建套接字时,我希望使用网络名称(如'wlan0‘或'eth0')进行连接,而不是使用IP地址。在JAVA中,我可以通过以下代码轻松地完成这一任务:

代码语言:javascript
复制
//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,但是什么都没有用。

非常感谢!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-12-04 18:34:31

其实答案很简单。这与Idx在之前的回答中所做的类似:

代码语言:javascript
复制
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

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

谢谢你的帮助!

票数 2
EN

Stack Overflow用户

发布于 2013-11-09 23:26:01

您需要利卜勒及其python绑定:

代码语言:javascript
复制
#!/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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19872052

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档