Python How to get all external IPs with multiple NICs

What is the most efficient way to get the whole external IP address of a machine with multiple nics using python? I understand that the external server is not connected (I have one available), but I can’t find a way to find a good way to tell nic to use to connect (so I can use the for loop to iterate through different nics). Any tips on how best to do this?

+5
source share
5 answers

You must use netifaces . It is designed for cross-platform work on Mac OS XX, Linux and Windows.

>>> import netifaces as ni
>>> ni.interfaces()
['lo', 'eth0', 'eth1', 'vboxnet0', 'dummy1']
>>> ni.ifaddresses('eth0')
{17: [{'broadcast': 'ff:ff:ff:ff:ff:ff', 'addr': '00:02:55:7b:b2:f6'}], 2: [{'broadcast': '24.19.161.7', 'netmask': '255.255.255.248', 'addr': '24.19.161.6'}], 10: [{'netmask': 'ffff:ffff:ffff:ffff::', 'addr': 'fe80::202:55ff:fe7b:b2f6%eth0'}]}
>>> 
>>> ni.ifaddresses.__doc__
'Obtain information about the specified network interface.\n\nReturns a dict whose keys are equal to the address family constants,\ne.g. netifaces.AF_INET, and whose values are a list of addresses in\nthat family that are attached to the network interface.'
>>> # for the IPv4 address of eth0
>>> ni.ifaddresses('eth0')[2][0]['addr']
'24.19.161.6'

, , /usr/include/linux/socket.h ( Linux)...

#define AF_INET         2       /* Internet IP Protocol         */
#define AF_INET6        10      /* IP version 6                 */
#define AF_PACKET       17      /* Packet family                */
+9

. , IP-, NAT. , , , NAT .

+1

: WMI/PyWin32 (https://sourceforge.net/projects/pywin32/)

, IP- () Windows.

import wmi
c = wmi.WMI()

for interface in c.Win32_NetworkAdapterConfiguration(IPEnabled=1):
    print("Description: " + interface.Description)
    print("IP: " + str(interface.IPAddress[0]))
    print("MAC: " + str(interface.IPAddress[1]))

, Win32_NetworkAdapterConfiguration, : https://msdn.microsoft.com/en-us/library/aa394217(v=vs.85).aspx

+1

import socket
print socket.gethostbyname_ex(socket.gethostname())[2]
0

subprocess , ifconfig netstat:

>>> import subprocess
>>> print subprocess.check_output(['ifconfig'])
-1

All Articles