Three ways to get IP addresses from python

Source: Internet
Author: User
Tags get ip in python

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 ()

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.