python獲取公網ip,本地ip及所在國家城市等相關信息收藏


python獲取公網ip的幾種方式

  1.  
    from urllib2 import urlopen
  2.  
    my_ip = urlopen( 'http://ip.42.pl/raw').read()
  3.  
    print 'ip.42.pl', my_ip
  4.  
     
  5.  
    from json import load
  6.  
    from urllib2 import urlopen
  7.  
     
  8.  
    my_ip = load(urlopen( 'http://jsonip.com'))['ip']
  9.  
    print 'jsonip.com', my_ip
  10.  
     
  11.  
    from json import load
  12.  
    from urllib2 import urlopen
  13.  
     
  14.  
    my_ip = load(urlopen( 'http://httpbin.org/ip'))['origin']
  15.  
    print 'httpbin.org', my_ip
  16.  
     
  17.  
    from json import load
  18.  
    from urllib2 import urlopen
  19.  
     
  20.  
    my_ip = load(urlopen( 'https://api.ipify.org/?format=json'))['ip']
  21.  
    print 'api.ipify.org', my_ip
  22.  

 

python 獲取ip信息(國家、城市等)

 

python 獲取ip信息(國家、城市等)

 

安裝geoip2包:pip install geoip2
下載數據庫文件:http://geolite.maxmind.com/download/geoip/database/GeoLite2-Country.tar.gz
解壓出GeoLite2-City.mmdb文件
新建py文件,內容如下:

import geoip2.database

reader = geoip2.database.Reader('./GeoLite2-City.mmdb')  # mmdb文件路徑
c= reader.country('123.123.123.123')
print c.country.names   # 國家名
print c.country.code  # 國家代碼
# 其他信息看源碼
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

** 以下為配置自動更新數據庫的步驟 **

在github下載geoipupdate最新包:geoipupdate-3.1.1.tar.gz
解壓並安裝:

tar -zxvf geoipupdate-3.1.1.tar.gz
./configure
sudo make
sudo make install 
  • 1
  • 2
  • 3
  • 4

修改配置文件:/usr/local/etc/GeoIP.conf

# The following AccountID and LicenseKey are required placeholders.
# For geoipupdate versions earlier than 2.5.0, use UserId here instead of AccountID.
AccountID 0 
LicenseKey 000000000000 
 
# Include one or more of the following edition IDs: 
# * GeoLite2-City - GeoLite 2 City 
# * GeoLite2-Country - GeoLite2 Country 
# For geoipupdate versions earlier than 2.5.0, use ProductIds here instead of EditionIDs.
EditionIDs GeoLite2-City GeoLite2-Country
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

執行更新:
/usr/local/bin/geoipupdate

添加crontab實現每周更新:crontab -e
0 0 * * 0 /usr/local/bin/geoipupdate

 
 

python 獲取本機IP的三種方式

 

python獲取本機IP的方式

第一種:

復制代碼
#!/usr/bin/python 
   
import socket 
import fcntl 
import struct 
def get_ip_address(ifname):   s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) return socket.inet_ntoa(fcntl.ioctl(   s.fileno(),   0x8915, # SIOCGIFADDR   struct.pack('256s', ifname[:15]) )[20:24]) #get_ip_address('lo')環回地址 #get_ip_address('eth0')主機ip地址
復制代碼

第二種:

復制代碼
def get_local_ip(ifname):  
  import socket, fcntl, struct  
  s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)  
  inet = fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s', ifname[:15]))  
  ret = socket.inet_ntoa(inet[20:24])  
  return ret  
print(get_local_ip("eth0"))  
復制代碼

第三種:

import socket
print(socket.gethostbyname(socket.getfqdn(socket.gethostname())))

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM