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信息(国家、城市等)
https://blog.csdn.net/qf0129/article/details/83145765
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())))