[英]Python, How to get all external ip addresses with multiple NICs
使用python获取具有多个nics的机器的所有外部ip地址的最有效方法是什么? 我知道需要一个外部服务器(我有一个可用)但是我无法找到一种方法来找到一个指定用于连接的nic的好方法(所以我可以使用for循环来遍历各种网络)。 有关最佳方法的任何建议吗?
你应该使用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 */
必需: 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 : Win32_NetworkAdapterConfiguration
( v = Win32_NetworkAdapterConfiguration
对于一般情况,没有解决方案。 考虑本地计算机位于具有两个执行NAT的IP地址的计算机后面的情况。 您可以将本地界面更改为您喜欢的任何内容,但您不太可能说服NAT计算机对其传出连接做出不同的路由决策。
获取所有NIC的地址,无需任何外部包
import socket
print socket.gethostbyname_ex(socket.gethostname())[2]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.