使用python获取具有多个网卡的机器的所有外部IP地址的最有效方法是什么?我知道需要一个外部服务器(我有一个可用的)但我无法找到一种方法来找到一种指定用于连接的 nic 的好方法(所以我可以使用 for 循环遍历各种 nic )。关于解决此问题的最佳方法有什么建议吗?
问问题
5511 次
5 回答
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 */
于 2011-11-27T16:31:28.353 回答
1
对于一般情况,没有解决方案。考虑本地机器位于具有两个执行 NAT 的 IP 地址的机器后面的情况。您可以将本地接口更改为您喜欢的任何内容,但您不太可能说服 NAT 机器对其传出连接做出不同的路由决定。
于 2011-11-26T23:11:10.330 回答
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
于 2016-10-05T12:51:53.093 回答
0
获取所有网卡的地址,无需任何外部包
import socket
print socket.gethostbyname_ex(socket.gethostname())[2]
于 2014-07-10T09:32:25.500 回答
-1
使用subprocess 模块连接到您常用的系统工具,例如ifconfig或netstat:
>>> import subprocess
>>> print subprocess.check_output(['ifconfig'])
于 2011-11-26T21:20:49.443 回答