python 获取本机出口ip

获取出口ip和归属地的程序。还是不大了解python的decode和encode  尴尬



#coding: utf-8
import urllib2,re


def getMyIp():
    try:
        rawTxt = urllib2.urlopen('http://1111.ip138.com/ic.asp').read()
    except:
        return None, None
    rawTxt = rawTxt.decode('gb2312')
    addr = re.search(u'来自:.*</center>', rawTxt).group(0)
    addr = addr[3:len(addr)-9]
    ip = re.search('\d+\.\d+\.\d+\.\d+', rawTxt).group(0)
    return ip, addr


ip, addr = getMyIp()
print ip, addr


====================================我是华丽的分隔线==========================

【改进】
1.增加两种异常捕获
2.增加超时设置,时间为60秒。实际应用中,如果不添加超时,出现超时情况时程序可以卡住几天不往下执行 囧
[code=python]
def getLocalIp():
    ''' 访问ip138.com,获取出口ip和归属地  '''
    try:
        rawStr = urllib2.urlopen("http://1111.ip138.com/ic.asp", timeout = 60).read()
    except urllib2.HTTPError,e:
        print "Error Code", e.code, "  ", e.read()
        return str(e.code), str(e.read())
    except urllib2.URLError, e:
        print "Failed to reach the server ", e.reason
        return "URLError", str(e.reason)
    except Exception, e:
        print "Exception ", e
        return "Exception", str(e)
        
    rawStr = rawStr.decode('gbk')
    ip = re.search('\d+\.\d+\.\d+\.\d+',rawStr).group(0)
    addr = re.search(u'来自:.*</center>',rawStr).group(0)
    return (ip, addr[3:len(addr)-9])
[/code]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值