可能重复:
查找使用Python的STDLIB本地IP地址
为了让我的本地IP地址我做socket.gethostbyname(socket.gethostname())
但它给我的答案127.0.0.1
。 如果我做an_existing_socket.getsockname()[0]
我得到的答案0.0.0.0
。
我需要我的“真实”的IP地址(例如192.168.XX)修改配置文件。 我怎样才能得到它呢?
可能重复:
查找使用Python的STDLIB本地IP地址
为了让我的本地IP地址我做socket.gethostbyname(socket.gethostname())
但它给我的答案127.0.0.1
。 如果我做an_existing_socket.getsockname()[0]
我得到的答案0.0.0.0
。
我需要我的“真实”的IP地址(例如192.168.XX)修改配置文件。 我怎样才能得到它呢?
我一般都用这个代码:
import os
import socket
if os.name != "nt":
import fcntl
import struct
def get_interface_ip(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s',
ifname[:15]))[20:24])
def get_lan_ip():
ip = socket.gethostbyname(socket.gethostname())
if ip.startswith("127.") and os.name != "nt":
interfaces = [
"eth0",
"eth1",
"eth2",
"wlan0",
"wlan1",
"wifi0",
"ath0",
"ath1",
"ppp0",
]
for ifname in interfaces:
try:
ip = get_interface_ip(ifname)
break
except IOError:
pass
return ip
我不知道它的起源,但它适用于Linux / Windows的。
编辑:
该代码使用由smerlin在这个计算器的问题。
还有就是你可以用一个漂亮的模块。 其所谓的netifaces。 只是做一个点子安装netifaces成用于测试的virtualenv中,并尝试下面的代码:
import netifaces
interfaces = netifaces.interfaces()
for i in interfaces:
if i == 'lo':
continue
iface = netifaces.ifaddresses(i).get(netifaces.AF_INET)
if iface != None:
for j in iface:
print j['addr']
这一切都取决于你的环境。 如果你仅仅使用附加了一个IP地址一个接口,你可以简单地做:
netifaces.ifaddresses('eth0')[netifaces.AF_INET][0]['addr']
如果你是一个NAT后面,想知道你的公网IP地址,你可以使用这样的:
import urllib2
ret = urllib2.urlopen('https://enabledns.com/ip')
print ret.read()
希望这可以帮助。