简体   繁体   English

使用IP地址在python中查找位置

[英]Using IP address to find location in python

I'm using this python code to get the users ip address: 我正在使用以下python代码获取用户的IP地址:

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

and using this to find their location: 并使用它找到他们的位置:

import socket
print socket.gethostbyname(socket.gethostname())
import urllib
response = urllib.urlopen('http://api.hostip.info/get_html.php?   ip=xxx&position=true').read()
print(response)

Could someone please help me find a way to get the ip and then put it into the second part of the code. 有人可以帮我找到获取ip的方法,然后将其放入代码的第二部分。 The program should find the users ip without them doing anything and then show the location. 该程序应查找用户ip,而无需他们做任何事情,然后显示位置。

Thanks. 谢谢。

There are several ways to do this kind of string manipulation in Python: 有几种方法可以在Python中进行这种字符串操作:

ip = socket.gethostbyname(socket.gethostname())

url = "http://api.hostip.info/get_html.php?ip=" + ip + "&position=true"
url = "http://api.hostip.info/get_html.php?ip=%s&position=true" % ip
url = "http://api.hostip.info/get_html.php?ip=xxx&position=true".replace("xxx", ip)
url = "http://api.hostip.info/get_html.php?ip={}&position=true".format(ip)

Pick one... the last three vary mainly by what token is going to be replaced by the IP address: %s , xxx (like you have in your question), or {} . 选择一个...后三个主要不同,主要取决于将由IP地址替换的令牌是: %sxxx (就像您在问题中一样)或{} For what it's worth, the last option is considered "the best way" nowadays. 就其价值而言,最后一种选择被认为是当今的“最佳方法”。

The rest of it you seem to have a pretty good handle on. 其余的您似乎都处理得很好。

I would suggest looking into the Geoip library. 我建议研究一下Geoip库。 it has a pretty straight forward module called geolite2. 它有一个非常简单的模块geolite2。 example: 例:

from geoip import geolite2

match = geolite2.lookup('10.10.10.10')
print('Country: '+match.country)
print('timezone: '+match.timezone)
...

there are functions for you to use if you want too look for the host ip without user input ! 如果您也想在没有用户输入的情况下寻找主机ip,则可以使用一些功能! it is pretty well documented here http://pythonhosted.org/python-geoip/ Hope this helps you out ! 在此处http://pythonhosted.org/python-geoip/上有很好的文档记录,希望这对您有所帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM