The way to get an IP address in Python is simple, we can only do it with the gethostbyname and gethostbyname_ex two functions, and of course we can use the public network API to implement it.
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 |
|
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 |
|
#!/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
code is as follows |
&nbs P; |
#!/usr/bin/env python Import re,urllib2 Class Get_public_i P: 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 () |