Python,如何获取多个网卡的所有外部IP地址
怎样用Python高效地获取一台有多个网卡的机器的所有外部IP地址?我知道需要一个外部服务器(我有一个可以用),但我找不到一个好的方法来指定要用哪个网卡进行连接(这样我就可以用循环来遍历不同的网卡)。有没有什么建议,告诉我该怎么做比较好?
5 个回答
1
需要的东西: WMI / PyWin32 (https://sourceforge.net/projects/pywin32/)
使用下面的代码片段可以获取Windows上网络适配器的IP地址。
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
一般来说,这种情况是没有解决办法的。想象一下,如果你的电脑在一个有两个IP地址的机器后面,这个机器在做网络地址转换(NAT)。你可以随便改你电脑上的网络设置,但说实话,想要让那个做NAT的机器改变它对外连接的路由选择,几乎是不可能的。
9
你应该使用netifaces这个库。它是为了在Mac OS X、Linux和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 */