[英]bind/connect to network interface card using python
我正在嘗試連接/綁定到特定的網絡接口卡(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,但沒有任何工作。
非常感謝你!!!
實際上答案很簡單。 它類似於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
在我得到“機器人地址”后,我可以像普通插座一樣綁定/連接它們。
謝謝您的幫助!
你需要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.