Python code for obtaining IP addresses in Linux-Python tutorial

Source: Internet
Author: User
This article mainly introduces the code for Python to obtain IP addresses in Linux. For more information about how to obtain IP addresses in lnmp one-key installation package, see: if the server only has a private IP address and no public IP address, the obtained IP address (that is, the private IP address) cannot be used to determine the location of the server, therefore, the gateway address is used to determine whether the server is in China or abroad (the yum source is automatically set to 163 for domestic users to download quickly. in this case, the gateway address needs to be obtained ); if the server has a public IP address, the obtained IP address can be used to directly determine the geographical location of the server.

Obtain the server IP address. if there is a public IP address, retrieve the public IP address. if there is no public IP address, retrieve the private IP address.
The following is a script for obtaining local IP addresses using shell:

IP=`ifconfig | grep 'inet addr:' | cut -d: -f2 | grep -v ^10\. | grep -v ^192\.168 | grep -v ^172\. | \grep -v ^127\. | awk '{print $1}' | awk '{print;exit}'` [ ! -n "$IP" ] && IP=`ifconfig | grep 'inet addr:' | cut -d: -f2 | grep -v ^127\. | \awk '{print $1}' | awk '{print;exit}'`

Python: get_local_ip.py:

#!/usr/bin/env pythonimport socketdef Get_local_ip(): """ Returns the actual ip of the local machine. This code figures out what source address would be used if some traffic were to be sent out to some well known address on the Internet. In this case, a Google DNS server is used, but the specific address does not matter much. No traffic is actually sent. """ try:  csock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)  csock.connect(('8.8.8.8', 80))  (addr, port) = csock.getsockname()  csock.close()  return addr except socket.error:  return "127.0.0.1" if __name__ == "__main__": local_IP = Get_local_ip()  print local_IP

Obtain the Gateway address directly without a public address (used to determine the geographic location of the IP address ):Get_public_ip.py

#!/usr/bin/env pythonimport re,urllib2class Get_public_ip: def getip(self):  try:   myip = self.visit("http://www.whereismyip.com/")  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()

Determine the geographic location of the server IP address:Get_ip_area.py

#!/usr/bin/env python#coding:utf-8try: import sys,urllib2,json apiurl = "http://ip.taobao.com/service/getIpInfo.php?ip=%s" % sys.argv[1]  content = urllib2.urlopen(apiurl).read() data = json.loads(content)['data'] code = json.loads(content)['code'] if code == 0:  print data['country_id'] else:  print dataexcept: print "Usage:%s IP" % sys.argv[0]

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.