The use of dial-up Internet, there are generally a local IP and an extranet IP, using Python can easily get these two IP
Use the gethostbyname and GETHOSTBYNAME_EX two functions to implement
The code is as follows |
Copy Code |
Import socket Localip = Socket.gethostbyname (Socket.gethostname ()) #这个得到本地ip Print "Local ip:%s"%localip IPList = SOCKET.GETHOSTBYNAME_EX (Socket.gethostname ()) For I in IPList: If I!= localip: print "External ip:%s"%i |
Get local IP Address
The code is as follows |
Copy Code |
#!/usr/bin/python
Import socket Import struct Import Fcntl
def getip (ethname):
S=socket.socket (socket.af_inet, socket. SOCK_DGRAM)
Return Socket.inet_ntoa (Fcntl.ioctl (S.fileno (), 0x8915, Struct.pack (' 256s ', ethname[:15])) [20:24])
If __name__== ' __main__ ':
Print GetIP (' eth0 ') |
Method Two, public network address direct access to IP
The code is as follows |
Copy Code |
#!/usr/bin/env python Import Re,urllib2 Class Get_public_ip: def getip (self): Try Myip = Self.visit ("http://www.111cn.net/") Except Try Myip = Self.visit ("http://www.ip138.com/ip2city.asp") 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) if __name__ = = "__main__": Getmyip = Get_public_ip () Print Getmyip.getip () |