user2913139
user2913139

Reputation: 627

python: how to check egress interface

I need to send a packet from my python script. I have a destination ip address. I need:
- egress interface name which is usually default route (i need it for sniffing response)
- ip address of that interface (i need to use it in my application payload)

How can i do it from python ?

Thanks,

Upvotes: 0

Views: 1387

Answers (1)

RyPeck
RyPeck

Reputation: 8167

Pynetinfo seems to be your best bet. This is a small sample on my machine. Your results will differ, but you will of course have a default gateway.

>>> import netinfo
>>> netinfo.get_routes()
({'dest': '0.0.0.0', 'netmask': '0.0.0.0', 'gateway': '192.168.0.1', 'dev': 'wlan1'}, 
{'dest': '169.254.0.0', 'netmask': '255.255.0.0', 'gateway': '0.0.0.0', 'dev': 'wlan1'}, 
{'dest': '192.168.0.0', 'netmask': '255.255.255.0', 'gateway': '0.0.0.0', 'dev': 'wlan1'})
>>> default_gateway = 
...[route for route in netinfo.get_routes() if route['dest'] == '0.0.0.0'][0]
>>> default_gateway['gateway']
'192.168.0.1'
>>> default_gateway['dev']
'wlan1'

As for getting the IP address of that interface...

>>> import netifaces
>>> netifaces.ifaddresses(default_gateway['dev'])[netifaces.AF_INET]
[{'broadcast': '192.168.0.255', 'netmask': '255.255.255.0', 'addr': '192.168.0.9'}]

For getting the interface that a IP packet would use with a given destination, on my Linux system. I'm not sure of another way.

>>> dst = "127.0.0.1"
>>> p = subprocess.Popen(["ip", "route", "get", dst], stdout=subprocess.PIPE)
>>> p.stdout.read()
'local 127.0.0.1 dev lo  src 127.0.0.1 \n    cache <local> \n'

Upvotes: 2

Related Questions