python获取本机hostname与外网ip(示例)

发布时间:2019-09-01编辑:脚本学堂
分享二个python代码,一是获取本机的hostname,一是取得外网的Ip地址,学习下python urllib2与socket模块的用法。

1,python获取外网IP地址
 

复制代码 代码示例:
import re,urllib2
class Getmyip:
    def getip(self):
        try:
            myip = self.visit("http://www.ip138.com/ip2city.asp")
            return myip
        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()
            asd=re.search('d+.d+.d+.d+',str).group(0)
            return asd
      
getmyip = Getmyip()
localip = getmyip.getip()
print localip

2,获取本地IP地址与hostanme
1)、windows和linux
 

复制代码 代码示例:

import socket

localIP=socket.gethostbyname(socket.gethostname())
print "local ip:%s "%localIP

ipList=socket.gethostbyname_ex(socket.gethostname())
for i in ipList:
    if i!=localIP:
        print "external IP:%s"%i
 

2)、linux系统中
 

复制代码 代码示例:

import socket,fcntl,struct

def get_ip_address(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])

print get_ip_address('eth0')