Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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. In JAVA I can do this easily with the following code:

//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. Any suggestions on how to do this?

I was using sockopt and the AF_CAN, but nothing is working.

Thank you very much!!!

like image 288
Pototo Avatar asked Oct 20 '22 21:10

Pototo


2 Answers

Actually the answer is very simple. And its similar to what Idx did in the previous answer:

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!

like image 77
Pototo Avatar answered Oct 23 '22 11:10

Pototo


You need libnl and its python bindings:

#!/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
like image 30
ldx Avatar answered Oct 23 '22 09:10

ldx