1

I'm using this python code to get the users ip address:

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. The program should find the users ip without them doing anything and then show the location.

Thanks.

2 Answers 2

6

There are several ways to do this kind of string manipulation in 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{}. 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.

Sign up to request clarification or add additional context in comments.

1 Comment

@kindall, I am getting unknown country and unknown city, what to do...?
0

I would suggest looking into the Geoip library. it has a pretty straight forward module called 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 ! it is pretty well documented here http://pythonhosted.org/python-geoip/ Hope this helps you out !

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.