Linux under Python to get IP address code

  • 2020-04-02 14:27:40
  • OfStack

The LNMP a key installation package, need to get the IP address, there are two situations: if the server is only the private network address no public address, this time to get the IP (i.e., the private network address) cannot be used to determine the location of the server, and then take the gateway address is used to judge the server at home and abroad, in order to make the domestic users to quickly download script, yum source automatically set to 163, this situation will need to access gateway address); If the server has a public network address, the obtained IP address can be used to directly determine the server's geographic location.

Get server IP, if there is a public network address to take the public network address, no public network address to take the private network address
Here's how I used the shell to get the local IP script:


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 version: get_local_ip.py:


#!/usr/bin/env python
import socket
def 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

Get the gateway address directly if there is no public address (used to determine the geographical location of IP address) : Get_public_ip. Py


#!/usr/bin/env python
import re,urllib2
class 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 IP location of the server: Get_ip_area. Py


#!/usr/bin/env python
#coding:utf-8
try:
 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 data
except:
 print "Usage:%s IP" % sys.argv[0]

Related articles: