2011-09-02 121 views
0

在Python中是否有一个函数来获取给定网络接口的IP地址? 有没有一个命令行程序可以做到这一点?如何获得给定网络接口的IP地址?

我想获取en1的IP地址。

这是我的机器上ifconfig的结果。

$ ifconfig 
lo0: flags=8049<UP,LOOPBACK,RUNNING,MULTICAST> mtu 16384 
    inet6 ::1 prefixlen 128 
    inet6 fe80::1%lo0 prefixlen 64 scopeid 0x1 
    inet 127.0.0.1 netmask 0xff000000 
gif0: flags=8010<POINTOPOINT,MULTICAST> mtu 1280 
stf0: flags=0<> mtu 1280 
en0: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500 
    ether 00:23:32:be:4e:90 
    media: autoselect 
    status: inactive 
en1: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500 
    ether 00:23:6c:7e:3e:0c 
    inet6 fe80::223:6cff:fe7e:3e0c%en1 prefixlen 64 scopeid 0x5 
    inet 192.168.1.70 netmask 0xffffff00 broadcast 192.168.1.255 
    media: autoselect 
    status: active 
vmnet1: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500 
    ether 00:50:56:c0:00:01 
    inet 172.16.64.1 netmask 0xffffff00 broadcast 172.16.64.255 
vmnet8: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500 
    ether 00:50:56:c0:00:08 
    inet 172.16.174.1 netmask 0xffffff00 broadcast 172.16.174.255 
vboxnet0: flags=8842<BROADCAST,RUNNING,SIMPLEX,MULTICAST> mtu 1500 
    ether 0a:00:27:00:00:00 
+0

请参阅http://stackoverflow.com/questions/166506/finding-local-ip-addresses-using-pythons-stdlib –

+0

可能的重复[如何从接口获取物理接口IP地址](http:///stackoverflow.com/questions/6243276/how-to-get-the-physical-interface-ip-address-from-an-interface) – zeekay

回答

2

$ sudo的PIP安装netifaces

$蟒蛇

的Python 2.6.1(R261:67515,2010年6月24日,21点47分49秒) [GCC 4.2.1(苹果公司。build 5646)] on darwin 输入“help”,“copyright”,“credits”或“license”以获取更多信息。

进口netifaces

netifaces.ifaddresses( 'EN0')

{18:[{ '地址':'10:9A:DD: 52:89:dc'}],2:[{'broadcast':'10 .188.55.255','netmask':'255.255.254.0','addr':'10 .188.55.130'}],30:[{ netmask':'ffff:ffff:ffff:ffff ::','addr':'fe80 :: 129a:ddff:fe52:89dc%en0'}]