How do I get the external IP of a socket in Python?

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?


Asked by: Brad470 | Posted: 06-10-2021






Answer 1

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.

Answered by: Miranda282 | Posted: 07-11-2021



Answer 2

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.

Answered by: Audrey701 | Posted: 07-11-2021



Answer 3

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()

Answered by: Marcus727 | Posted: 07-11-2021



Answer 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)

Answered by: Stella952 | Posted: 07-11-2021



Answer 5

import socket

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

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

s.getsockname()

Answered by: Alford865 | Posted: 07-11-2021



Answer 6

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

Answered by: Audrey684 | Posted: 07-11-2021



Answer 7

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}')

Answered by: Emma352 | Posted: 07-11-2021



Answer 8

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]

Answered by: Sydney250 | Posted: 07-11-2021



Answer 9


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")

Answered by: Emily788 | Posted: 07-11-2021



Similar questions

Python: Read a file (from an external server)

Can you tell me how to code a Python script which reads a file from an external server? I look for something similar to PHP's file_get_contents() or file() function. It would be great if someone could post the entire code for such a script. Thanks in advance!


How to call an external program in python and retrieve the output and return code?

How can I call an external program with a python script and retrieve the output and return code?


External classes in Python

I'm just beginning Python, and I'd like to use an external RSS class. Where do I put that class and how do I import it? I'd like to eventually be able to share python programs.


python - How to I get scons to invoke an external script?

I'm trying to use scons to build a latex document. In particular, I want to get scons to invoke a python program that generates a file containing a table that is \input{} into the main document. I've looked over the scons documentation but it is not immediately clear to me what I need to do. What I wish to achieve is essentially what you would get with this makefile: document.pdf: table.tex pdf...


How to include external Python code to use in other files?

If you have a collection of methods in a file, is there a way to include those files in another file, but call them without any prefix (i.e. file prefix)? So if I have: [Math.py] def Calculate ( num ) How do I call it like this: [Tool.py] using Math.py for i in range ( 5 ) : Calculate ( i )


c - Calling an external program from python

So I have this shell script: echo "Enter text to be classified, hit return to run classification." read text if [ `echo "$text" | sed -r 's/ +/ /g' | bin/stupidfilter data/c_rbf` = "1.000000" ] then echo "Text is not likely to be stupid." fi if [ `echo "$text" | sed -r 's/ +/ /g' | bin/stupidfilter data/c_rbf` = "0.000000" ] then echo "Text is likely to be stupid." fi I would like ...


python - How to get output from external command combine with Pipe

I have command like this. wmctrl -lp | awk '/gedit/ { print $1 }' And I want its output within python script, i tried this code &gt;&gt;&gt; import subprocess &gt;&gt;&gt; proc = subprocess.Popen(["wmctrl -lp", "|","awk '/gedit/ {print $1}"], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) &gt;&gt;&gt; proc.stdout.readline() '0x0160001b -1 6504 beer-laptop x-...


sql - Limit calls to external database with Python CGI

I've got a Python CGI script that pulls data from a GPS service; I'd like this information to be updated on the webpage about once every 10s (the max allowed by the GPS service's TOS). But there could be, say, 100 users viewing the webpage at once, all calling the script. I think the users' scripts need to grab data from a buffer page that itself only upates once every ten seconds. How can I make this buffer page...


python - Opening links in external browser in Amarok 1.4

I've tried asking this question on the KDE development forum, but haven't received a satisfying answer so far. I've developed a Python script for Amarok 1.4 which retrieves upcoming events for the currently playing artist...


python - How to access external object within event handler?

As the title says, I'm grabbing the cursor location within a motion triggered event handler in Tkinter. I'd like to update an existing label widget with the location. However, I cannot for the life of me figure out how to edit the Label text field (or any external object for that matter) within the event handler. From what I understand, event is the only argument passed to the handler, which means I c...






Still can't find your answer? Check out these communities...



PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python



top