Getting a machine's external IP address with Python
Looking for a better way to get a machines current external IP #... Below works, but would rather not rely on an outside site to gather the information ... I am restricted to using standard Python 2.5.1 libraries bundled with Mac OS X 10.5.x
import os
import urllib2
def check_in():
fqn = os.uname()[1]
ext_ip = urllib2.urlopen('http://whatismyip.org').read()
print ("Asset: %s " % fqn, "Checking in from IP#: %s " % ext_ip)
python standard-library
add a comment |
Looking for a better way to get a machines current external IP #... Below works, but would rather not rely on an outside site to gather the information ... I am restricted to using standard Python 2.5.1 libraries bundled with Mac OS X 10.5.x
import os
import urllib2
def check_in():
fqn = os.uname()[1]
ext_ip = urllib2.urlopen('http://whatismyip.org').read()
print ("Asset: %s " % fqn, "Checking in from IP#: %s " % ext_ip)
python standard-library
related: Discovering public IP programatically
– jfs
Feb 27 '14 at 17:23
add a comment |
Looking for a better way to get a machines current external IP #... Below works, but would rather not rely on an outside site to gather the information ... I am restricted to using standard Python 2.5.1 libraries bundled with Mac OS X 10.5.x
import os
import urllib2
def check_in():
fqn = os.uname()[1]
ext_ip = urllib2.urlopen('http://whatismyip.org').read()
print ("Asset: %s " % fqn, "Checking in from IP#: %s " % ext_ip)
python standard-library
Looking for a better way to get a machines current external IP #... Below works, but would rather not rely on an outside site to gather the information ... I am restricted to using standard Python 2.5.1 libraries bundled with Mac OS X 10.5.x
import os
import urllib2
def check_in():
fqn = os.uname()[1]
ext_ip = urllib2.urlopen('http://whatismyip.org').read()
print ("Asset: %s " % fqn, "Checking in from IP#: %s " % ext_ip)
python standard-library
python standard-library
edited Nov 24 '17 at 0:29
cit
asked Feb 22 '10 at 14:36
citcit
77641836
77641836
related: Discovering public IP programatically
– jfs
Feb 27 '14 at 17:23
add a comment |
related: Discovering public IP programatically
– jfs
Feb 27 '14 at 17:23
related: Discovering public IP programatically
– jfs
Feb 27 '14 at 17:23
related: Discovering public IP programatically
– jfs
Feb 27 '14 at 17:23
add a comment |
22 Answers
22
active
oldest
votes
If you are behind a router which obtains the external IP, I'm afraid you have no other option but to use external service like you do. If the router itself has some query interface, you can use it, but the solution will be very environment-specific and unreliable.
add a comment |
I liked the http://ipify.org. They even provide Python code for using their API.
# This example requires the requests library be installed. You can learn more
# about the Requests library here: http://docs.python-requests.org/en/latest/
from requests import get
ip = get('https://api.ipify.org').text
print 'My public IP address is:', ip
add a comment |
Python3, using nothing else but the standard library
As mentioned before, one cannot get around using an external service of some sorts in order to discover the external IP address of your router.
Here is how it is done with python3
, using nothing else but the standard library:
import urllib.request
external_ip = urllib.request.urlopen('https://ident.me').read().decode('utf8')
print(external_ip)
add a comment |
You should use the UPnP protocol to query your router for this information. Most importantly, this does not rely on an external service, which all the other answers to this question seem to suggest.
There's a Python library called miniupnp which can do this, see e.g. miniupnpc/testupnpigd.py.
pip install miniupnpc
Based on their example you should be able to do something like this:
import miniupnpc
u = miniupnpc.UPnP()
u.discoverdelay = 200
u.discover()
u.selectigd()
print('external ip address: {}'.format(u.externalipaddress()))
1
This works even when you are connected to a VPN. Thanks
– pumazi
Dec 25 '18 at 20:55
add a comment |
If you think and external source is too unreliable, you could pool a few different services. For most ip lookup pages they require you to scrape html, but a few of them that have created lean pages for scripts like yours - also so they can reduce the hits on their sites:
automation.whatismyip.com/n09230945.asp (Update: whatismyip has taken this service down)- whatismyip.org
1
The automation link was useful while it lasted, thanks
– Anake
May 13 '13 at 11:47
13
This one might be ideal: icanhazip.com
– Mark Embling
Jun 23 '13 at 11:12
add a comment |
In my opinion the simplest solution is
f = requests.request('GET', 'http://myip.dnsomatic.com')
ip = f.text
Thats all.
1
It is probably worth mentioning you need toimport requests
. See pypi.python.org/pypi/requests
– John
Sep 11 '15 at 15:19
Does not technically answer the question since "Requests officially supports Python 2.6–2.7 & 3.3–3.7, and runs great on PyPy." However, it is still useful to others.
– Jerod
Mar 23 '17 at 15:41
add a comment |
I tried most of the other answers on this question here and came to find that most of the services used were defunct except one.
Here is a script that should do the trick and download only a minimal amount of information:
#!/usr/bin/env python
import urllib
import re
def get_external_ip():
site = urllib.urlopen("http://checkip.dyndns.org/").read()
grab = re.findall('([0-9]+.[0-9]+.[0-9]+.[0-9]+)', site)
address = grab[0]
return address
if __name__ == '__main__':
print( get_external_ip() )
Regex is broken. Should be d{1,3}.
– Thanos Diacakis
Sep 30 '13 at 17:49
add a comment |
import requests
import re
def getMyExtIp():
try:
res = requests.get("http://whatismyip.org")
myIp = re.compile('(d{1,3}.){3}d{1,3}').search(res.text).group()
if myIp != "":
return myIp
except:
pass
return "n/a"
Damn this is a bit faster than just using BeautifulSoup, thanks
– Eli
Oct 9 '17 at 16:59
add a comment |
If the machine is being a firewall then your solution is a very sensible one: the alternative being able to query the firewall which ends-up being very dependent on the type of firewall (if at all possible).
add a comment |
The most simple (non python) working solution I can think of is
wget -q -O- icanhazip.com
I'd like to add a very short Python3 solution which makes use of the JSON API of http://hostip.info.
from urllib.request import urlopen
import json
url = 'http://api.hostip.info/get_json.php'
info = json.loads(urlopen(url).read().decode('utf-8'))
print(info['ip'])
You can of course add some error checking, a timeout condition and some convenience:
#!/usr/bin/env python3
from urllib.request import urlopen
from urllib.error import URLError
import json
try:
url = 'http://api.hostip.info/get_json.php'
info = json.loads(urlopen(url, timeout = 15).read().decode('utf-8'))
print(info['ip'])
except URLError as e:
print(e.reason, end=' ') # e.g. 'timed out'
print('(are you connected to the internet?)')
except KeyboardInterrupt:
pass
add a comment |
In [1]: import stun
stun.get_ip_info()
('Restric NAT', 'xx.xx.xx.xx', 55320)
Where does the stun library come from?
– Score_Under
Feb 28 at 16:17
add a comment |
Working with Python 2.7.6 and 2.7.13
import urllib2
req = urllib2.Request('http://icanhazip.com', data=None)
response = urllib2.urlopen(req, timeout=5)
print(response.read())
add a comment |
Just as an alternative. Here's a script you can try out.
add a comment |
As Sunny has suggested, its not possible in general to get external ip-address being inside a network without any help from external services.
Have a look at the following tutorial which covers exactly the same thing. I guess it works for Python 2.5.X.
http://codetempo.com/programming/python/monitoring-ip-addresses-of-your-computer-start-up-script-on-linux-ubuntu
It says that tutorial is for Linux but works for other platforms with python too.
add a comment |
ipWebCode = urllib.request.urlopen("http://ip.nefsc.noaa.gov").read().decode("utf8")
ipWebCode=ipWebCode.split("color=red> ")
ipWebCode = ipWebCode[1]
ipWebCode = ipWebCode.split("</font>")
externalIp = ipWebCode[0]
this is a short snippet I had written for another program. The trick was finding a simple enough website so that dissecting the html wasn't a pain.
add a comment |
Here's another alternative script.
def track_ip():
"""
Returns Dict with the following keys:
- ip
- latlong
- country
- city
- user-agent
"""
conn = httplib.HTTPConnection("www.trackip.net")
conn.request("GET", "/ip?json")
resp = conn.getresponse()
print resp.status, resp.reason
if resp.status == 200:
ip = json.loads(resp.read())
else:
print 'Connection Error: %s' % resp.reason
conn.close()
return ip
EDIT: Don't forget to import httplib and json
This answer used to work for me, but the packages break when updating using conda, so I've abandoned this answer for a simplier solution @Hors Sujet in stackoverflow.com/questions/24508730/…
– nagordon
Jul 13 '15 at 13:09
add a comment |
If you're just writing for yourself and not for a generalized application, you might be able to find the address on the setup page for your router and then scrape it from that page's html. This worked fine for me with my SMC router. One read and one simple RE search and I've found it.
My particular interest in doing this was to let me know my home IP address when I was away from home, so I could get back in via VNC. A few more lines of Python stores the address in Dropbox for outside access, and even emails me if it sees a change. I've scheduled it to happen on boot and once an hour thereafter.
add a comment |
Use this script :
import urllib, json
data = json.loads(urllib.urlopen("http://ip.jsontest.com/").read())
print data["ip"]
Without json :
import urllib, re
data = re.search('"([0-9.]*)"', urllib.urlopen("http://ip.jsontest.com/").read()).group(1)
print data
add a comment |
There are a few other ways that do not rely on Python checking an external web site, however the OS can. Your primary issue here, is that even if you were not using Python, if you were using the command line, there are no "built-in" commands that can just simply tell you the external (WAN) IP. Commands such as "ip addr show" and "ifconfig -a" show you the server's IP address's within the network. Only the router actually holds the external IP. However, there are ways to find the external IP address (WAN IP) from the command line.
These examples are:
http://ipecho.net/plain ; echo
curl ipinfo.io/ip
dig +short myip.opendns.com @resolver1.opendns.com
dig TXT +short o-o.myaddr.l.google.com @ns1.google.com
Therefore, the python code would be:
import os
ip = os.popen('wget -qO- http://ipecho.net/plain ; echo').readlines(-1)[0].strip()
print ip
OR
import os
iN, out, err = os.popen3('curl ipinfo.io/ip')
iN.close() ; err.close()
ip = out.read().strip()
print ip
OR
import os
ip = os.popen('dig +short myip.opendns.com @resolver1.opendns.com').readlines(-1)[0].strip()
print ip
Or, plug any other of the examples above, into a command like os.popen, os.popen2, os.popen3, or os.system.
add a comment |
If you don't want to use external services (IP websites, etc.) You can use the UPnP Protocol.
Do to that we use a simple UPnP client library (https://github.com/flyte/upnpclient)
Install:
pip install upnpclient
Simple Code:
import upnpclient
devices = upnpclient.discover()
if(len(devices) > 0):
externalIP = devices[0].WANIPConn1.GetExternalIPAddress()
print(externalIP)
else:
print('No Connected network interface detected')
Full Code (to get more information as mentioned in the github readme)
In [1]: import upnpclient
In [2]: devices = upnpclient.discover()
In [3]: devices
Out[3]:
[<Device 'OpenWRT router'>,
<Device 'Harmony Hub'>,
<Device 'walternate: root'>]
In [4]: d = devices[0]
In [5]: d.WANIPConn1.GetStatusInfo()
Out[5]:
{'NewConnectionStatus': 'Connected',
'NewLastConnectionError': 'ERROR_NONE',
'NewUptime': 14851479}
In [6]: d.WANIPConn1.GetNATRSIPStatus()
Out[6]: {'NewNATEnabled': True, 'NewRSIPAvailable': False}
In [7]: d.WANIPConn1.GetExternalIPAddress()
Out[7]: {'NewExternalIPAddress': '123.123.123.123'}
add a comment |
Use requests module:
import requests
myip = requests.get('https://www.wikipedia.org').headers['X-Client-IP']
print("n[+] Public IP: "+myip)
add a comment |
As simple as running this in Python3:
import os
externalIP = os.popen('curl -s ifconfig.me').readline()
print(externalIP)
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f2311510%2fgetting-a-machines-external-ip-address-with-python%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
22 Answers
22
active
oldest
votes
22 Answers
22
active
oldest
votes
active
oldest
votes
active
oldest
votes
If you are behind a router which obtains the external IP, I'm afraid you have no other option but to use external service like you do. If the router itself has some query interface, you can use it, but the solution will be very environment-specific and unreliable.
add a comment |
If you are behind a router which obtains the external IP, I'm afraid you have no other option but to use external service like you do. If the router itself has some query interface, you can use it, but the solution will be very environment-specific and unreliable.
add a comment |
If you are behind a router which obtains the external IP, I'm afraid you have no other option but to use external service like you do. If the router itself has some query interface, you can use it, but the solution will be very environment-specific and unreliable.
If you are behind a router which obtains the external IP, I'm afraid you have no other option but to use external service like you do. If the router itself has some query interface, you can use it, but the solution will be very environment-specific and unreliable.
edited Jan 22 '14 at 17:23
Tshepang
6,1701772114
6,1701772114
answered Feb 22 '10 at 14:41
Sunny MilenovSunny Milenov
17.4k46697
17.4k46697
add a comment |
add a comment |
I liked the http://ipify.org. They even provide Python code for using their API.
# This example requires the requests library be installed. You can learn more
# about the Requests library here: http://docs.python-requests.org/en/latest/
from requests import get
ip = get('https://api.ipify.org').text
print 'My public IP address is:', ip
add a comment |
I liked the http://ipify.org. They even provide Python code for using their API.
# This example requires the requests library be installed. You can learn more
# about the Requests library here: http://docs.python-requests.org/en/latest/
from requests import get
ip = get('https://api.ipify.org').text
print 'My public IP address is:', ip
add a comment |
I liked the http://ipify.org. They even provide Python code for using their API.
# This example requires the requests library be installed. You can learn more
# about the Requests library here: http://docs.python-requests.org/en/latest/
from requests import get
ip = get('https://api.ipify.org').text
print 'My public IP address is:', ip
I liked the http://ipify.org. They even provide Python code for using their API.
# This example requires the requests library be installed. You can learn more
# about the Requests library here: http://docs.python-requests.org/en/latest/
from requests import get
ip = get('https://api.ipify.org').text
print 'My public IP address is:', ip
answered Mar 24 '16 at 16:44
mario1uamario1ua
604815
604815
add a comment |
add a comment |
Python3, using nothing else but the standard library
As mentioned before, one cannot get around using an external service of some sorts in order to discover the external IP address of your router.
Here is how it is done with python3
, using nothing else but the standard library:
import urllib.request
external_ip = urllib.request.urlopen('https://ident.me').read().decode('utf8')
print(external_ip)
add a comment |
Python3, using nothing else but the standard library
As mentioned before, one cannot get around using an external service of some sorts in order to discover the external IP address of your router.
Here is how it is done with python3
, using nothing else but the standard library:
import urllib.request
external_ip = urllib.request.urlopen('https://ident.me').read().decode('utf8')
print(external_ip)
add a comment |
Python3, using nothing else but the standard library
As mentioned before, one cannot get around using an external service of some sorts in order to discover the external IP address of your router.
Here is how it is done with python3
, using nothing else but the standard library:
import urllib.request
external_ip = urllib.request.urlopen('https://ident.me').read().decode('utf8')
print(external_ip)
Python3, using nothing else but the standard library
As mentioned before, one cannot get around using an external service of some sorts in order to discover the external IP address of your router.
Here is how it is done with python3
, using nothing else but the standard library:
import urllib.request
external_ip = urllib.request.urlopen('https://ident.me').read().decode('utf8')
print(external_ip)
edited Feb 9 '18 at 10:00
answered Jan 2 '17 at 20:20
Serge StroobandtSerge Stroobandt
11.2k75361
11.2k75361
add a comment |
add a comment |
You should use the UPnP protocol to query your router for this information. Most importantly, this does not rely on an external service, which all the other answers to this question seem to suggest.
There's a Python library called miniupnp which can do this, see e.g. miniupnpc/testupnpigd.py.
pip install miniupnpc
Based on their example you should be able to do something like this:
import miniupnpc
u = miniupnpc.UPnP()
u.discoverdelay = 200
u.discover()
u.selectigd()
print('external ip address: {}'.format(u.externalipaddress()))
1
This works even when you are connected to a VPN. Thanks
– pumazi
Dec 25 '18 at 20:55
add a comment |
You should use the UPnP protocol to query your router for this information. Most importantly, this does not rely on an external service, which all the other answers to this question seem to suggest.
There's a Python library called miniupnp which can do this, see e.g. miniupnpc/testupnpigd.py.
pip install miniupnpc
Based on their example you should be able to do something like this:
import miniupnpc
u = miniupnpc.UPnP()
u.discoverdelay = 200
u.discover()
u.selectigd()
print('external ip address: {}'.format(u.externalipaddress()))
1
This works even when you are connected to a VPN. Thanks
– pumazi
Dec 25 '18 at 20:55
add a comment |
You should use the UPnP protocol to query your router for this information. Most importantly, this does not rely on an external service, which all the other answers to this question seem to suggest.
There's a Python library called miniupnp which can do this, see e.g. miniupnpc/testupnpigd.py.
pip install miniupnpc
Based on their example you should be able to do something like this:
import miniupnpc
u = miniupnpc.UPnP()
u.discoverdelay = 200
u.discover()
u.selectigd()
print('external ip address: {}'.format(u.externalipaddress()))
You should use the UPnP protocol to query your router for this information. Most importantly, this does not rely on an external service, which all the other answers to this question seem to suggest.
There's a Python library called miniupnp which can do this, see e.g. miniupnpc/testupnpigd.py.
pip install miniupnpc
Based on their example you should be able to do something like this:
import miniupnpc
u = miniupnpc.UPnP()
u.discoverdelay = 200
u.discover()
u.selectigd()
print('external ip address: {}'.format(u.externalipaddress()))
edited Jul 9 '18 at 4:49
SomeGuyOnAComputer
1,24121432
1,24121432
answered Dec 29 '16 at 18:08
VegardVegard
1,026821
1,026821
1
This works even when you are connected to a VPN. Thanks
– pumazi
Dec 25 '18 at 20:55
add a comment |
1
This works even when you are connected to a VPN. Thanks
– pumazi
Dec 25 '18 at 20:55
1
1
This works even when you are connected to a VPN. Thanks
– pumazi
Dec 25 '18 at 20:55
This works even when you are connected to a VPN. Thanks
– pumazi
Dec 25 '18 at 20:55
add a comment |
If you think and external source is too unreliable, you could pool a few different services. For most ip lookup pages they require you to scrape html, but a few of them that have created lean pages for scripts like yours - also so they can reduce the hits on their sites:
automation.whatismyip.com/n09230945.asp (Update: whatismyip has taken this service down)- whatismyip.org
1
The automation link was useful while it lasted, thanks
– Anake
May 13 '13 at 11:47
13
This one might be ideal: icanhazip.com
– Mark Embling
Jun 23 '13 at 11:12
add a comment |
If you think and external source is too unreliable, you could pool a few different services. For most ip lookup pages they require you to scrape html, but a few of them that have created lean pages for scripts like yours - also so they can reduce the hits on their sites:
automation.whatismyip.com/n09230945.asp (Update: whatismyip has taken this service down)- whatismyip.org
1
The automation link was useful while it lasted, thanks
– Anake
May 13 '13 at 11:47
13
This one might be ideal: icanhazip.com
– Mark Embling
Jun 23 '13 at 11:12
add a comment |
If you think and external source is too unreliable, you could pool a few different services. For most ip lookup pages they require you to scrape html, but a few of them that have created lean pages for scripts like yours - also so they can reduce the hits on their sites:
automation.whatismyip.com/n09230945.asp (Update: whatismyip has taken this service down)- whatismyip.org
If you think and external source is too unreliable, you could pool a few different services. For most ip lookup pages they require you to scrape html, but a few of them that have created lean pages for scripts like yours - also so they can reduce the hits on their sites:
automation.whatismyip.com/n09230945.asp (Update: whatismyip has taken this service down)- whatismyip.org
edited May 7 '13 at 11:03
answered Feb 22 '10 at 14:52
Thomas AhleThomas Ahle
21.8k166596
21.8k166596
1
The automation link was useful while it lasted, thanks
– Anake
May 13 '13 at 11:47
13
This one might be ideal: icanhazip.com
– Mark Embling
Jun 23 '13 at 11:12
add a comment |
1
The automation link was useful while it lasted, thanks
– Anake
May 13 '13 at 11:47
13
This one might be ideal: icanhazip.com
– Mark Embling
Jun 23 '13 at 11:12
1
1
The automation link was useful while it lasted, thanks
– Anake
May 13 '13 at 11:47
The automation link was useful while it lasted, thanks
– Anake
May 13 '13 at 11:47
13
13
This one might be ideal: icanhazip.com
– Mark Embling
Jun 23 '13 at 11:12
This one might be ideal: icanhazip.com
– Mark Embling
Jun 23 '13 at 11:12
add a comment |
In my opinion the simplest solution is
f = requests.request('GET', 'http://myip.dnsomatic.com')
ip = f.text
Thats all.
1
It is probably worth mentioning you need toimport requests
. See pypi.python.org/pypi/requests
– John
Sep 11 '15 at 15:19
Does not technically answer the question since "Requests officially supports Python 2.6–2.7 & 3.3–3.7, and runs great on PyPy." However, it is still useful to others.
– Jerod
Mar 23 '17 at 15:41
add a comment |
In my opinion the simplest solution is
f = requests.request('GET', 'http://myip.dnsomatic.com')
ip = f.text
Thats all.
1
It is probably worth mentioning you need toimport requests
. See pypi.python.org/pypi/requests
– John
Sep 11 '15 at 15:19
Does not technically answer the question since "Requests officially supports Python 2.6–2.7 & 3.3–3.7, and runs great on PyPy." However, it is still useful to others.
– Jerod
Mar 23 '17 at 15:41
add a comment |
In my opinion the simplest solution is
f = requests.request('GET', 'http://myip.dnsomatic.com')
ip = f.text
Thats all.
In my opinion the simplest solution is
f = requests.request('GET', 'http://myip.dnsomatic.com')
ip = f.text
Thats all.
answered Jun 27 '15 at 18:48
Jit9Jit9
849
849
1
It is probably worth mentioning you need toimport requests
. See pypi.python.org/pypi/requests
– John
Sep 11 '15 at 15:19
Does not technically answer the question since "Requests officially supports Python 2.6–2.7 & 3.3–3.7, and runs great on PyPy." However, it is still useful to others.
– Jerod
Mar 23 '17 at 15:41
add a comment |
1
It is probably worth mentioning you need toimport requests
. See pypi.python.org/pypi/requests
– John
Sep 11 '15 at 15:19
Does not technically answer the question since "Requests officially supports Python 2.6–2.7 & 3.3–3.7, and runs great on PyPy." However, it is still useful to others.
– Jerod
Mar 23 '17 at 15:41
1
1
It is probably worth mentioning you need to
import requests
. See pypi.python.org/pypi/requests– John
Sep 11 '15 at 15:19
It is probably worth mentioning you need to
import requests
. See pypi.python.org/pypi/requests– John
Sep 11 '15 at 15:19
Does not technically answer the question since "Requests officially supports Python 2.6–2.7 & 3.3–3.7, and runs great on PyPy." However, it is still useful to others.
– Jerod
Mar 23 '17 at 15:41
Does not technically answer the question since "Requests officially supports Python 2.6–2.7 & 3.3–3.7, and runs great on PyPy." However, it is still useful to others.
– Jerod
Mar 23 '17 at 15:41
add a comment |
I tried most of the other answers on this question here and came to find that most of the services used were defunct except one.
Here is a script that should do the trick and download only a minimal amount of information:
#!/usr/bin/env python
import urllib
import re
def get_external_ip():
site = urllib.urlopen("http://checkip.dyndns.org/").read()
grab = re.findall('([0-9]+.[0-9]+.[0-9]+.[0-9]+)', site)
address = grab[0]
return address
if __name__ == '__main__':
print( get_external_ip() )
Regex is broken. Should be d{1,3}.
– Thanos Diacakis
Sep 30 '13 at 17:49
add a comment |
I tried most of the other answers on this question here and came to find that most of the services used were defunct except one.
Here is a script that should do the trick and download only a minimal amount of information:
#!/usr/bin/env python
import urllib
import re
def get_external_ip():
site = urllib.urlopen("http://checkip.dyndns.org/").read()
grab = re.findall('([0-9]+.[0-9]+.[0-9]+.[0-9]+)', site)
address = grab[0]
return address
if __name__ == '__main__':
print( get_external_ip() )
Regex is broken. Should be d{1,3}.
– Thanos Diacakis
Sep 30 '13 at 17:49
add a comment |
I tried most of the other answers on this question here and came to find that most of the services used were defunct except one.
Here is a script that should do the trick and download only a minimal amount of information:
#!/usr/bin/env python
import urllib
import re
def get_external_ip():
site = urllib.urlopen("http://checkip.dyndns.org/").read()
grab = re.findall('([0-9]+.[0-9]+.[0-9]+.[0-9]+)', site)
address = grab[0]
return address
if __name__ == '__main__':
print( get_external_ip() )
I tried most of the other answers on this question here and came to find that most of the services used were defunct except one.
Here is a script that should do the trick and download only a minimal amount of information:
#!/usr/bin/env python
import urllib
import re
def get_external_ip():
site = urllib.urlopen("http://checkip.dyndns.org/").read()
grab = re.findall('([0-9]+.[0-9]+.[0-9]+.[0-9]+)', site)
address = grab[0]
return address
if __name__ == '__main__':
print( get_external_ip() )
edited Sep 8 '14 at 2:02
user3663132
435
435
answered Jun 5 '13 at 23:18
Christian JensenChristian Jensen
35524
35524
Regex is broken. Should be d{1,3}.
– Thanos Diacakis
Sep 30 '13 at 17:49
add a comment |
Regex is broken. Should be d{1,3}.
– Thanos Diacakis
Sep 30 '13 at 17:49
Regex is broken. Should be d{1,3}.
– Thanos Diacakis
Sep 30 '13 at 17:49
Regex is broken. Should be d{1,3}.
– Thanos Diacakis
Sep 30 '13 at 17:49
add a comment |
import requests
import re
def getMyExtIp():
try:
res = requests.get("http://whatismyip.org")
myIp = re.compile('(d{1,3}.){3}d{1,3}').search(res.text).group()
if myIp != "":
return myIp
except:
pass
return "n/a"
Damn this is a bit faster than just using BeautifulSoup, thanks
– Eli
Oct 9 '17 at 16:59
add a comment |
import requests
import re
def getMyExtIp():
try:
res = requests.get("http://whatismyip.org")
myIp = re.compile('(d{1,3}.){3}d{1,3}').search(res.text).group()
if myIp != "":
return myIp
except:
pass
return "n/a"
Damn this is a bit faster than just using BeautifulSoup, thanks
– Eli
Oct 9 '17 at 16:59
add a comment |
import requests
import re
def getMyExtIp():
try:
res = requests.get("http://whatismyip.org")
myIp = re.compile('(d{1,3}.){3}d{1,3}').search(res.text).group()
if myIp != "":
return myIp
except:
pass
return "n/a"
import requests
import re
def getMyExtIp():
try:
res = requests.get("http://whatismyip.org")
myIp = re.compile('(d{1,3}.){3}d{1,3}').search(res.text).group()
if myIp != "":
return myIp
except:
pass
return "n/a"
answered Mar 31 '17 at 4:39
Nikita RovdaNikita Rovda
211
211
Damn this is a bit faster than just using BeautifulSoup, thanks
– Eli
Oct 9 '17 at 16:59
add a comment |
Damn this is a bit faster than just using BeautifulSoup, thanks
– Eli
Oct 9 '17 at 16:59
Damn this is a bit faster than just using BeautifulSoup, thanks
– Eli
Oct 9 '17 at 16:59
Damn this is a bit faster than just using BeautifulSoup, thanks
– Eli
Oct 9 '17 at 16:59
add a comment |
If the machine is being a firewall then your solution is a very sensible one: the alternative being able to query the firewall which ends-up being very dependent on the type of firewall (if at all possible).
add a comment |
If the machine is being a firewall then your solution is a very sensible one: the alternative being able to query the firewall which ends-up being very dependent on the type of firewall (if at all possible).
add a comment |
If the machine is being a firewall then your solution is a very sensible one: the alternative being able to query the firewall which ends-up being very dependent on the type of firewall (if at all possible).
If the machine is being a firewall then your solution is a very sensible one: the alternative being able to query the firewall which ends-up being very dependent on the type of firewall (if at all possible).
answered Feb 22 '10 at 14:39
jldupontjldupont
56.6k44176291
56.6k44176291
add a comment |
add a comment |
The most simple (non python) working solution I can think of is
wget -q -O- icanhazip.com
I'd like to add a very short Python3 solution which makes use of the JSON API of http://hostip.info.
from urllib.request import urlopen
import json
url = 'http://api.hostip.info/get_json.php'
info = json.loads(urlopen(url).read().decode('utf-8'))
print(info['ip'])
You can of course add some error checking, a timeout condition and some convenience:
#!/usr/bin/env python3
from urllib.request import urlopen
from urllib.error import URLError
import json
try:
url = 'http://api.hostip.info/get_json.php'
info = json.loads(urlopen(url, timeout = 15).read().decode('utf-8'))
print(info['ip'])
except URLError as e:
print(e.reason, end=' ') # e.g. 'timed out'
print('(are you connected to the internet?)')
except KeyboardInterrupt:
pass
add a comment |
The most simple (non python) working solution I can think of is
wget -q -O- icanhazip.com
I'd like to add a very short Python3 solution which makes use of the JSON API of http://hostip.info.
from urllib.request import urlopen
import json
url = 'http://api.hostip.info/get_json.php'
info = json.loads(urlopen(url).read().decode('utf-8'))
print(info['ip'])
You can of course add some error checking, a timeout condition and some convenience:
#!/usr/bin/env python3
from urllib.request import urlopen
from urllib.error import URLError
import json
try:
url = 'http://api.hostip.info/get_json.php'
info = json.loads(urlopen(url, timeout = 15).read().decode('utf-8'))
print(info['ip'])
except URLError as e:
print(e.reason, end=' ') # e.g. 'timed out'
print('(are you connected to the internet?)')
except KeyboardInterrupt:
pass
add a comment |
The most simple (non python) working solution I can think of is
wget -q -O- icanhazip.com
I'd like to add a very short Python3 solution which makes use of the JSON API of http://hostip.info.
from urllib.request import urlopen
import json
url = 'http://api.hostip.info/get_json.php'
info = json.loads(urlopen(url).read().decode('utf-8'))
print(info['ip'])
You can of course add some error checking, a timeout condition and some convenience:
#!/usr/bin/env python3
from urllib.request import urlopen
from urllib.error import URLError
import json
try:
url = 'http://api.hostip.info/get_json.php'
info = json.loads(urlopen(url, timeout = 15).read().decode('utf-8'))
print(info['ip'])
except URLError as e:
print(e.reason, end=' ') # e.g. 'timed out'
print('(are you connected to the internet?)')
except KeyboardInterrupt:
pass
The most simple (non python) working solution I can think of is
wget -q -O- icanhazip.com
I'd like to add a very short Python3 solution which makes use of the JSON API of http://hostip.info.
from urllib.request import urlopen
import json
url = 'http://api.hostip.info/get_json.php'
info = json.loads(urlopen(url).read().decode('utf-8'))
print(info['ip'])
You can of course add some error checking, a timeout condition and some convenience:
#!/usr/bin/env python3
from urllib.request import urlopen
from urllib.error import URLError
import json
try:
url = 'http://api.hostip.info/get_json.php'
info = json.loads(urlopen(url, timeout = 15).read().decode('utf-8'))
print(info['ip'])
except URLError as e:
print(e.reason, end=' ') # e.g. 'timed out'
print('(are you connected to the internet?)')
except KeyboardInterrupt:
pass
edited May 13 '14 at 13:26
answered May 9 '14 at 10:39
timgebtimgeb
51.1k116694
51.1k116694
add a comment |
add a comment |
In [1]: import stun
stun.get_ip_info()
('Restric NAT', 'xx.xx.xx.xx', 55320)
Where does the stun library come from?
– Score_Under
Feb 28 at 16:17
add a comment |
In [1]: import stun
stun.get_ip_info()
('Restric NAT', 'xx.xx.xx.xx', 55320)
Where does the stun library come from?
– Score_Under
Feb 28 at 16:17
add a comment |
In [1]: import stun
stun.get_ip_info()
('Restric NAT', 'xx.xx.xx.xx', 55320)
In [1]: import stun
stun.get_ip_info()
('Restric NAT', 'xx.xx.xx.xx', 55320)
edited Mar 12 '15 at 12:06
answered Mar 26 '14 at 22:10
enthus1astenthus1ast
1,5051115
1,5051115
Where does the stun library come from?
– Score_Under
Feb 28 at 16:17
add a comment |
Where does the stun library come from?
– Score_Under
Feb 28 at 16:17
Where does the stun library come from?
– Score_Under
Feb 28 at 16:17
Where does the stun library come from?
– Score_Under
Feb 28 at 16:17
add a comment |
Working with Python 2.7.6 and 2.7.13
import urllib2
req = urllib2.Request('http://icanhazip.com', data=None)
response = urllib2.urlopen(req, timeout=5)
print(response.read())
add a comment |
Working with Python 2.7.6 and 2.7.13
import urllib2
req = urllib2.Request('http://icanhazip.com', data=None)
response = urllib2.urlopen(req, timeout=5)
print(response.read())
add a comment |
Working with Python 2.7.6 and 2.7.13
import urllib2
req = urllib2.Request('http://icanhazip.com', data=None)
response = urllib2.urlopen(req, timeout=5)
print(response.read())
Working with Python 2.7.6 and 2.7.13
import urllib2
req = urllib2.Request('http://icanhazip.com', data=None)
response = urllib2.urlopen(req, timeout=5)
print(response.read())
answered Mar 26 '18 at 17:40
user3526918user3526918
25638
25638
add a comment |
add a comment |
Just as an alternative. Here's a script you can try out.
add a comment |
Just as an alternative. Here's a script you can try out.
add a comment |
Just as an alternative. Here's a script you can try out.
Just as an alternative. Here's a script you can try out.
answered Feb 22 '10 at 14:51
ghostdog74ghostdog74
222k42212303
222k42212303
add a comment |
add a comment |
As Sunny has suggested, its not possible in general to get external ip-address being inside a network without any help from external services.
Have a look at the following tutorial which covers exactly the same thing. I guess it works for Python 2.5.X.
http://codetempo.com/programming/python/monitoring-ip-addresses-of-your-computer-start-up-script-on-linux-ubuntu
It says that tutorial is for Linux but works for other platforms with python too.
add a comment |
As Sunny has suggested, its not possible in general to get external ip-address being inside a network without any help from external services.
Have a look at the following tutorial which covers exactly the same thing. I guess it works for Python 2.5.X.
http://codetempo.com/programming/python/monitoring-ip-addresses-of-your-computer-start-up-script-on-linux-ubuntu
It says that tutorial is for Linux but works for other platforms with python too.
add a comment |
As Sunny has suggested, its not possible in general to get external ip-address being inside a network without any help from external services.
Have a look at the following tutorial which covers exactly the same thing. I guess it works for Python 2.5.X.
http://codetempo.com/programming/python/monitoring-ip-addresses-of-your-computer-start-up-script-on-linux-ubuntu
It says that tutorial is for Linux but works for other platforms with python too.
As Sunny has suggested, its not possible in general to get external ip-address being inside a network without any help from external services.
Have a look at the following tutorial which covers exactly the same thing. I guess it works for Python 2.5.X.
http://codetempo.com/programming/python/monitoring-ip-addresses-of-your-computer-start-up-script-on-linux-ubuntu
It says that tutorial is for Linux but works for other platforms with python too.
answered Nov 24 '11 at 2:04
MicrokernelMicrokernel
70931233
70931233
add a comment |
add a comment |
ipWebCode = urllib.request.urlopen("http://ip.nefsc.noaa.gov").read().decode("utf8")
ipWebCode=ipWebCode.split("color=red> ")
ipWebCode = ipWebCode[1]
ipWebCode = ipWebCode.split("</font>")
externalIp = ipWebCode[0]
this is a short snippet I had written for another program. The trick was finding a simple enough website so that dissecting the html wasn't a pain.
add a comment |
ipWebCode = urllib.request.urlopen("http://ip.nefsc.noaa.gov").read().decode("utf8")
ipWebCode=ipWebCode.split("color=red> ")
ipWebCode = ipWebCode[1]
ipWebCode = ipWebCode.split("</font>")
externalIp = ipWebCode[0]
this is a short snippet I had written for another program. The trick was finding a simple enough website so that dissecting the html wasn't a pain.
add a comment |
ipWebCode = urllib.request.urlopen("http://ip.nefsc.noaa.gov").read().decode("utf8")
ipWebCode=ipWebCode.split("color=red> ")
ipWebCode = ipWebCode[1]
ipWebCode = ipWebCode.split("</font>")
externalIp = ipWebCode[0]
this is a short snippet I had written for another program. The trick was finding a simple enough website so that dissecting the html wasn't a pain.
ipWebCode = urllib.request.urlopen("http://ip.nefsc.noaa.gov").read().decode("utf8")
ipWebCode=ipWebCode.split("color=red> ")
ipWebCode = ipWebCode[1]
ipWebCode = ipWebCode.split("</font>")
externalIp = ipWebCode[0]
this is a short snippet I had written for another program. The trick was finding a simple enough website so that dissecting the html wasn't a pain.
answered Feb 5 '13 at 3:23
Malcolm BoydMalcolm Boyd
415
415
add a comment |
add a comment |
Here's another alternative script.
def track_ip():
"""
Returns Dict with the following keys:
- ip
- latlong
- country
- city
- user-agent
"""
conn = httplib.HTTPConnection("www.trackip.net")
conn.request("GET", "/ip?json")
resp = conn.getresponse()
print resp.status, resp.reason
if resp.status == 200:
ip = json.loads(resp.read())
else:
print 'Connection Error: %s' % resp.reason
conn.close()
return ip
EDIT: Don't forget to import httplib and json
This answer used to work for me, but the packages break when updating using conda, so I've abandoned this answer for a simplier solution @Hors Sujet in stackoverflow.com/questions/24508730/…
– nagordon
Jul 13 '15 at 13:09
add a comment |
Here's another alternative script.
def track_ip():
"""
Returns Dict with the following keys:
- ip
- latlong
- country
- city
- user-agent
"""
conn = httplib.HTTPConnection("www.trackip.net")
conn.request("GET", "/ip?json")
resp = conn.getresponse()
print resp.status, resp.reason
if resp.status == 200:
ip = json.loads(resp.read())
else:
print 'Connection Error: %s' % resp.reason
conn.close()
return ip
EDIT: Don't forget to import httplib and json
This answer used to work for me, but the packages break when updating using conda, so I've abandoned this answer for a simplier solution @Hors Sujet in stackoverflow.com/questions/24508730/…
– nagordon
Jul 13 '15 at 13:09
add a comment |
Here's another alternative script.
def track_ip():
"""
Returns Dict with the following keys:
- ip
- latlong
- country
- city
- user-agent
"""
conn = httplib.HTTPConnection("www.trackip.net")
conn.request("GET", "/ip?json")
resp = conn.getresponse()
print resp.status, resp.reason
if resp.status == 200:
ip = json.loads(resp.read())
else:
print 'Connection Error: %s' % resp.reason
conn.close()
return ip
EDIT: Don't forget to import httplib and json
Here's another alternative script.
def track_ip():
"""
Returns Dict with the following keys:
- ip
- latlong
- country
- city
- user-agent
"""
conn = httplib.HTTPConnection("www.trackip.net")
conn.request("GET", "/ip?json")
resp = conn.getresponse()
print resp.status, resp.reason
if resp.status == 200:
ip = json.loads(resp.read())
else:
print 'Connection Error: %s' % resp.reason
conn.close()
return ip
EDIT: Don't forget to import httplib and json
answered Jan 19 '14 at 12:59
dr4ke616dr4ke616
764
764
This answer used to work for me, but the packages break when updating using conda, so I've abandoned this answer for a simplier solution @Hors Sujet in stackoverflow.com/questions/24508730/…
– nagordon
Jul 13 '15 at 13:09
add a comment |
This answer used to work for me, but the packages break when updating using conda, so I've abandoned this answer for a simplier solution @Hors Sujet in stackoverflow.com/questions/24508730/…
– nagordon
Jul 13 '15 at 13:09
This answer used to work for me, but the packages break when updating using conda, so I've abandoned this answer for a simplier solution @Hors Sujet in stackoverflow.com/questions/24508730/…
– nagordon
Jul 13 '15 at 13:09
This answer used to work for me, but the packages break when updating using conda, so I've abandoned this answer for a simplier solution @Hors Sujet in stackoverflow.com/questions/24508730/…
– nagordon
Jul 13 '15 at 13:09
add a comment |
If you're just writing for yourself and not for a generalized application, you might be able to find the address on the setup page for your router and then scrape it from that page's html. This worked fine for me with my SMC router. One read and one simple RE search and I've found it.
My particular interest in doing this was to let me know my home IP address when I was away from home, so I could get back in via VNC. A few more lines of Python stores the address in Dropbox for outside access, and even emails me if it sees a change. I've scheduled it to happen on boot and once an hour thereafter.
add a comment |
If you're just writing for yourself and not for a generalized application, you might be able to find the address on the setup page for your router and then scrape it from that page's html. This worked fine for me with my SMC router. One read and one simple RE search and I've found it.
My particular interest in doing this was to let me know my home IP address when I was away from home, so I could get back in via VNC. A few more lines of Python stores the address in Dropbox for outside access, and even emails me if it sees a change. I've scheduled it to happen on boot and once an hour thereafter.
add a comment |
If you're just writing for yourself and not for a generalized application, you might be able to find the address on the setup page for your router and then scrape it from that page's html. This worked fine for me with my SMC router. One read and one simple RE search and I've found it.
My particular interest in doing this was to let me know my home IP address when I was away from home, so I could get back in via VNC. A few more lines of Python stores the address in Dropbox for outside access, and even emails me if it sees a change. I've scheduled it to happen on boot and once an hour thereafter.
If you're just writing for yourself and not for a generalized application, you might be able to find the address on the setup page for your router and then scrape it from that page's html. This worked fine for me with my SMC router. One read and one simple RE search and I've found it.
My particular interest in doing this was to let me know my home IP address when I was away from home, so I could get back in via VNC. A few more lines of Python stores the address in Dropbox for outside access, and even emails me if it sees a change. I've scheduled it to happen on boot and once an hour thereafter.
answered May 4 '14 at 21:39
BruceBruce
11
11
add a comment |
add a comment |
Use this script :
import urllib, json
data = json.loads(urllib.urlopen("http://ip.jsontest.com/").read())
print data["ip"]
Without json :
import urllib, re
data = re.search('"([0-9.]*)"', urllib.urlopen("http://ip.jsontest.com/").read()).group(1)
print data
add a comment |
Use this script :
import urllib, json
data = json.loads(urllib.urlopen("http://ip.jsontest.com/").read())
print data["ip"]
Without json :
import urllib, re
data = re.search('"([0-9.]*)"', urllib.urlopen("http://ip.jsontest.com/").read()).group(1)
print data
add a comment |
Use this script :
import urllib, json
data = json.loads(urllib.urlopen("http://ip.jsontest.com/").read())
print data["ip"]
Without json :
import urllib, re
data = re.search('"([0-9.]*)"', urllib.urlopen("http://ip.jsontest.com/").read()).group(1)
print data
Use this script :
import urllib, json
data = json.loads(urllib.urlopen("http://ip.jsontest.com/").read())
print data["ip"]
Without json :
import urllib, re
data = re.search('"([0-9.]*)"', urllib.urlopen("http://ip.jsontest.com/").read()).group(1)
print data
answered Feb 29 '16 at 18:37
A-312A-312
7,09342755
7,09342755
add a comment |
add a comment |
There are a few other ways that do not rely on Python checking an external web site, however the OS can. Your primary issue here, is that even if you were not using Python, if you were using the command line, there are no "built-in" commands that can just simply tell you the external (WAN) IP. Commands such as "ip addr show" and "ifconfig -a" show you the server's IP address's within the network. Only the router actually holds the external IP. However, there are ways to find the external IP address (WAN IP) from the command line.
These examples are:
http://ipecho.net/plain ; echo
curl ipinfo.io/ip
dig +short myip.opendns.com @resolver1.opendns.com
dig TXT +short o-o.myaddr.l.google.com @ns1.google.com
Therefore, the python code would be:
import os
ip = os.popen('wget -qO- http://ipecho.net/plain ; echo').readlines(-1)[0].strip()
print ip
OR
import os
iN, out, err = os.popen3('curl ipinfo.io/ip')
iN.close() ; err.close()
ip = out.read().strip()
print ip
OR
import os
ip = os.popen('dig +short myip.opendns.com @resolver1.opendns.com').readlines(-1)[0].strip()
print ip
Or, plug any other of the examples above, into a command like os.popen, os.popen2, os.popen3, or os.system.
add a comment |
There are a few other ways that do not rely on Python checking an external web site, however the OS can. Your primary issue here, is that even if you were not using Python, if you were using the command line, there are no "built-in" commands that can just simply tell you the external (WAN) IP. Commands such as "ip addr show" and "ifconfig -a" show you the server's IP address's within the network. Only the router actually holds the external IP. However, there are ways to find the external IP address (WAN IP) from the command line.
These examples are:
http://ipecho.net/plain ; echo
curl ipinfo.io/ip
dig +short myip.opendns.com @resolver1.opendns.com
dig TXT +short o-o.myaddr.l.google.com @ns1.google.com
Therefore, the python code would be:
import os
ip = os.popen('wget -qO- http://ipecho.net/plain ; echo').readlines(-1)[0].strip()
print ip
OR
import os
iN, out, err = os.popen3('curl ipinfo.io/ip')
iN.close() ; err.close()
ip = out.read().strip()
print ip
OR
import os
ip = os.popen('dig +short myip.opendns.com @resolver1.opendns.com').readlines(-1)[0].strip()
print ip
Or, plug any other of the examples above, into a command like os.popen, os.popen2, os.popen3, or os.system.
add a comment |
There are a few other ways that do not rely on Python checking an external web site, however the OS can. Your primary issue here, is that even if you were not using Python, if you were using the command line, there are no "built-in" commands that can just simply tell you the external (WAN) IP. Commands such as "ip addr show" and "ifconfig -a" show you the server's IP address's within the network. Only the router actually holds the external IP. However, there are ways to find the external IP address (WAN IP) from the command line.
These examples are:
http://ipecho.net/plain ; echo
curl ipinfo.io/ip
dig +short myip.opendns.com @resolver1.opendns.com
dig TXT +short o-o.myaddr.l.google.com @ns1.google.com
Therefore, the python code would be:
import os
ip = os.popen('wget -qO- http://ipecho.net/plain ; echo').readlines(-1)[0].strip()
print ip
OR
import os
iN, out, err = os.popen3('curl ipinfo.io/ip')
iN.close() ; err.close()
ip = out.read().strip()
print ip
OR
import os
ip = os.popen('dig +short myip.opendns.com @resolver1.opendns.com').readlines(-1)[0].strip()
print ip
Or, plug any other of the examples above, into a command like os.popen, os.popen2, os.popen3, or os.system.
There are a few other ways that do not rely on Python checking an external web site, however the OS can. Your primary issue here, is that even if you were not using Python, if you were using the command line, there are no "built-in" commands that can just simply tell you the external (WAN) IP. Commands such as "ip addr show" and "ifconfig -a" show you the server's IP address's within the network. Only the router actually holds the external IP. However, there are ways to find the external IP address (WAN IP) from the command line.
These examples are:
http://ipecho.net/plain ; echo
curl ipinfo.io/ip
dig +short myip.opendns.com @resolver1.opendns.com
dig TXT +short o-o.myaddr.l.google.com @ns1.google.com
Therefore, the python code would be:
import os
ip = os.popen('wget -qO- http://ipecho.net/plain ; echo').readlines(-1)[0].strip()
print ip
OR
import os
iN, out, err = os.popen3('curl ipinfo.io/ip')
iN.close() ; err.close()
ip = out.read().strip()
print ip
OR
import os
ip = os.popen('dig +short myip.opendns.com @resolver1.opendns.com').readlines(-1)[0].strip()
print ip
Or, plug any other of the examples above, into a command like os.popen, os.popen2, os.popen3, or os.system.
edited Sep 19 '18 at 22:22
answered Sep 19 '18 at 18:14
PyTisPyTis
16328
16328
add a comment |
add a comment |
If you don't want to use external services (IP websites, etc.) You can use the UPnP Protocol.
Do to that we use a simple UPnP client library (https://github.com/flyte/upnpclient)
Install:
pip install upnpclient
Simple Code:
import upnpclient
devices = upnpclient.discover()
if(len(devices) > 0):
externalIP = devices[0].WANIPConn1.GetExternalIPAddress()
print(externalIP)
else:
print('No Connected network interface detected')
Full Code (to get more information as mentioned in the github readme)
In [1]: import upnpclient
In [2]: devices = upnpclient.discover()
In [3]: devices
Out[3]:
[<Device 'OpenWRT router'>,
<Device 'Harmony Hub'>,
<Device 'walternate: root'>]
In [4]: d = devices[0]
In [5]: d.WANIPConn1.GetStatusInfo()
Out[5]:
{'NewConnectionStatus': 'Connected',
'NewLastConnectionError': 'ERROR_NONE',
'NewUptime': 14851479}
In [6]: d.WANIPConn1.GetNATRSIPStatus()
Out[6]: {'NewNATEnabled': True, 'NewRSIPAvailable': False}
In [7]: d.WANIPConn1.GetExternalIPAddress()
Out[7]: {'NewExternalIPAddress': '123.123.123.123'}
add a comment |
If you don't want to use external services (IP websites, etc.) You can use the UPnP Protocol.
Do to that we use a simple UPnP client library (https://github.com/flyte/upnpclient)
Install:
pip install upnpclient
Simple Code:
import upnpclient
devices = upnpclient.discover()
if(len(devices) > 0):
externalIP = devices[0].WANIPConn1.GetExternalIPAddress()
print(externalIP)
else:
print('No Connected network interface detected')
Full Code (to get more information as mentioned in the github readme)
In [1]: import upnpclient
In [2]: devices = upnpclient.discover()
In [3]: devices
Out[3]:
[<Device 'OpenWRT router'>,
<Device 'Harmony Hub'>,
<Device 'walternate: root'>]
In [4]: d = devices[0]
In [5]: d.WANIPConn1.GetStatusInfo()
Out[5]:
{'NewConnectionStatus': 'Connected',
'NewLastConnectionError': 'ERROR_NONE',
'NewUptime': 14851479}
In [6]: d.WANIPConn1.GetNATRSIPStatus()
Out[6]: {'NewNATEnabled': True, 'NewRSIPAvailable': False}
In [7]: d.WANIPConn1.GetExternalIPAddress()
Out[7]: {'NewExternalIPAddress': '123.123.123.123'}
add a comment |
If you don't want to use external services (IP websites, etc.) You can use the UPnP Protocol.
Do to that we use a simple UPnP client library (https://github.com/flyte/upnpclient)
Install:
pip install upnpclient
Simple Code:
import upnpclient
devices = upnpclient.discover()
if(len(devices) > 0):
externalIP = devices[0].WANIPConn1.GetExternalIPAddress()
print(externalIP)
else:
print('No Connected network interface detected')
Full Code (to get more information as mentioned in the github readme)
In [1]: import upnpclient
In [2]: devices = upnpclient.discover()
In [3]: devices
Out[3]:
[<Device 'OpenWRT router'>,
<Device 'Harmony Hub'>,
<Device 'walternate: root'>]
In [4]: d = devices[0]
In [5]: d.WANIPConn1.GetStatusInfo()
Out[5]:
{'NewConnectionStatus': 'Connected',
'NewLastConnectionError': 'ERROR_NONE',
'NewUptime': 14851479}
In [6]: d.WANIPConn1.GetNATRSIPStatus()
Out[6]: {'NewNATEnabled': True, 'NewRSIPAvailable': False}
In [7]: d.WANIPConn1.GetExternalIPAddress()
Out[7]: {'NewExternalIPAddress': '123.123.123.123'}
If you don't want to use external services (IP websites, etc.) You can use the UPnP Protocol.
Do to that we use a simple UPnP client library (https://github.com/flyte/upnpclient)
Install:
pip install upnpclient
Simple Code:
import upnpclient
devices = upnpclient.discover()
if(len(devices) > 0):
externalIP = devices[0].WANIPConn1.GetExternalIPAddress()
print(externalIP)
else:
print('No Connected network interface detected')
Full Code (to get more information as mentioned in the github readme)
In [1]: import upnpclient
In [2]: devices = upnpclient.discover()
In [3]: devices
Out[3]:
[<Device 'OpenWRT router'>,
<Device 'Harmony Hub'>,
<Device 'walternate: root'>]
In [4]: d = devices[0]
In [5]: d.WANIPConn1.GetStatusInfo()
Out[5]:
{'NewConnectionStatus': 'Connected',
'NewLastConnectionError': 'ERROR_NONE',
'NewUptime': 14851479}
In [6]: d.WANIPConn1.GetNATRSIPStatus()
Out[6]: {'NewNATEnabled': True, 'NewRSIPAvailable': False}
In [7]: d.WANIPConn1.GetExternalIPAddress()
Out[7]: {'NewExternalIPAddress': '123.123.123.123'}
answered Nov 25 '18 at 9:55
EliEli
401622
401622
add a comment |
add a comment |
Use requests module:
import requests
myip = requests.get('https://www.wikipedia.org').headers['X-Client-IP']
print("n[+] Public IP: "+myip)
add a comment |
Use requests module:
import requests
myip = requests.get('https://www.wikipedia.org').headers['X-Client-IP']
print("n[+] Public IP: "+myip)
add a comment |
Use requests module:
import requests
myip = requests.get('https://www.wikipedia.org').headers['X-Client-IP']
print("n[+] Public IP: "+myip)
Use requests module:
import requests
myip = requests.get('https://www.wikipedia.org').headers['X-Client-IP']
print("n[+] Public IP: "+myip)
answered Feb 8 at 2:16
J0KER11J0KER11
463
463
add a comment |
add a comment |
As simple as running this in Python3:
import os
externalIP = os.popen('curl -s ifconfig.me').readline()
print(externalIP)
add a comment |
As simple as running this in Python3:
import os
externalIP = os.popen('curl -s ifconfig.me').readline()
print(externalIP)
add a comment |
As simple as running this in Python3:
import os
externalIP = os.popen('curl -s ifconfig.me').readline()
print(externalIP)
As simple as running this in Python3:
import os
externalIP = os.popen('curl -s ifconfig.me').readline()
print(externalIP)
answered Mar 2 at 11:21
JavDomGomJavDomGom
114
114
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f2311510%2fgetting-a-machines-external-ip-address-with-python%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
related: Discovering public IP programatically
– jfs
Feb 27 '14 at 17:23