python獲取公網ip的幾種方式
-
from urllib2 import urlopen
-
my_ip = urlopen( 'http://ip.42.pl/raw').read()
-
print 'ip.42.pl', my_ip
-
-
from json import load
-
from urllib2 import urlopen
-
-
my_ip = load(urlopen( 'http://jsonip.com'))['ip']
-
print 'jsonip.com', my_ip
-
-
from json import load
-
from urllib2 import urlopen
-
-
my_ip = load(urlopen( 'http://httpbin.org/ip'))['origin']
-
print 'httpbin.org', my_ip
-
-
from json import load
-
from urllib2 import urlopen
-
-
my_ip = load(urlopen( 'https://api.ipify.org/?format=json'))['ip']
-
print 'api.ipify.org', my_ip
-
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())))