10

When I call socket.getsockname() on a socket object, it returns a tuple of my machine's internal IP and the port. However, I would like to retrieve my external IP. What's the cheapest, most efficient manner of doing this?

1
  • Another great website that offers a no frills solution is to get an HTTP request from icanhazip.com Commented Jan 13, 2012 at 12:32

9 Answers 9

9

This isn't possible without cooperation from an external server, because there could be any number of NATs between you and the other computer. If it's a custom protocol, you could ask the other system to report what address it's connected to.

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

Comments

7

The only way I can think of that's guaranteed to give it to you is to hit a service like http://whatismyip.com/ to get it.

2 Comments

Not quite sure why this was voted down. This is IMHO the only way to get the external IP address of any system. Just because a router tells you what it thinks your IP address is, or what it thinks it's IP address is doesn't mean there isn't another NAT in place.
@MatthewSchinckel: +1 for mentioning another NAT. Also, different external services may see different external IPs e.g., I remember that to access a library site, I had to use a different route so that the site sees different (allowed) ip i.e., the public ip may depend on destination.
5

https://github.com/bobeirasa/mini-scripts/blob/master/externalip.py

'''
Finds your external IP address
'''

import urllib
import re

def get_ip():
    group = re.compile(u'(?P<ip>\d+\.\d+\.\d+\.\d+)').search(urllib.URLopener().open('http://jsonip.com/').read()).groupdict()
    return group['ip']

if __name__ == '__main__':
    print get_ip()

2 Comments

Was not aware of jsonip.com--thanks. Here's a little more "jsonic" variation of your answer (auto formatting is messing up the url): json.loads(urllib2.urlopen(urllib2.Request('jsonip.com', headers = {'Content-Type': 'application/json'})).read())['ip']
@Rafael Lopes The link was moved to https://jsonip.com/ (301 permanently). Btw. for me it works perfectly. In my case, the external IP in the response is in IPv6 format, which is fine. Nice one.
4

You'll need to use an external system to do this.

DuckDuckGo's IP answer will give you exactly what you want, and in JSON!

import requests

def detect_public_ip():
    try:
        # Use a get request for api.duckduckgo.com
        raw = requests.get('https://api.duckduckgo.com/?q=ip&format=json')
        # load the request as json, look for Answer.
        # split on spaces, find the 5th index ( as it starts at 0 ), which is the IP address
        answer = raw.json()["Answer"].split()[4]
    # if there are any connection issues, error out
    except Exception as e:
        return 'Error: {0}'.format(e)
    # otherwise, return answer
    else:
        return answer

public_ip = detect_public_ip()
print(public_ip)

Comments

3

The most simple method of getting a public IP is by using this

import requests

IP = requests.get('https://api.ipify.org/').text
print(f'Your IP is: {IP}')

Comments

2

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

s.connect(("msn.com",80))

s.getsockname()

Comments

1
print (urllib.urlopen('http://automation.whatismyip.com/n09230945.asp').read())

Comments

0

Using the address suggested in the source of http://whatismyip.com

import urllib
def get_my_ip_address():
    whatismyip = 'http://www.whatismyip.com/automation/n09230945.asp'
    return urllib.urlopen(whatismyip).readlines()[0]

1 Comment

note they say to not do this more than once every 300 seconds
0

You need to make connection to an external Server And Get Your Public IP From The Response


like this:

   import requests

   myPublic_IP = requests.get("http://wtfismyip.com/text").text.strip()

   print("\n[+] My Public IP: "+ myPublic_IP+"\n")

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.