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

2020-08-22 07:19发布

问题:

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:

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.



回答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.



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


回答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)


回答5:

import socket

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

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

s.getsockname()



回答6:

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


回答7:

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]


回答8:


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