天碰到这个问题,用Python获得本地IP地址,首先想到用socket.gethostbyname,代码如下:
程序代码:
import socket ip = socket.gethostbyname(socket.gethostname()) print ip
可惜这样并不完美,特别如果是ADSL拨号或者局域网上网会得到192.168.*.*这种内部IP。
好像Linux下面可以用:
程序代码:
import socket
import fcntl
import struct
def get_ip_address(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(
s.fileno(),
0x8915, # SIOCGIFADDR
struct.pack('256s', ifname[:15])
)[20:24])
print get_ip_address('lo')
print get_ip_address('eth0')
具体没试过,我主要写的是windows下面的应用,只能另寻他法。
WIndows:
#-*- coding: gb2312 -*-
#!c:Program Filespython252python.ex import re,urllib2 from subprocess import Popen, PIPE
print “本机的私网IP地址为:” + re.search(‘d+.d+.d+.d+’,Popen(‘ipconfig’, stdout=PIPE).stdout.read()).group(0)
print “本机的公网IP地址为:” + re.search(‘d+.d+.d+.d+’,urllib2.urlopen(“http://www.whereismyip.com”).read()).group(0)
运行结果如下:
本机的私网IP地址为:192.168.1.21
本机的公网IP地址为:219.135.212.16
找到一种windows和Linux下面通用的方法:
程序代码:
import re,urllib2
print re.search(‘d+.d+.d+.d+’,urllib2.urlopen(“http://www.whereismyip.com”).read()).group(0)
感觉有点山寨,访问专门显示自己IP的网站,然后采集它的内容,用正则分析提取出IP地址的字符串。
这样有个问题,如果访问的网站挂掉了,这程序就失灵了。
完美解决方案:
程序代码:
import re,urllib2
class Getmyip:
def getip(self):
try:
myip = self.visit("http://www.ip138.com/ip2city.asp")
except:
try:
myip = self.visit("http://www.bliao.com/ip.phtml")
except:
try:
myip = self.visit("http://www.whereismyip.com/")
except:
myip = "So sorry!!!"
return myip
def visit(self,url):
opener = urllib2.urlopen(url)
if url == opener.geturl():
str = opener.read()
return re.search('d+.d+.d+.d+',str).group(0)
getmyip = Getmyip()
localip = getmyip.getip()
print localip
转载请注明:爱开源 » Python获取本机IP(外网IP)的方法总结