如何在 Python 中获取套接字的外部 IP?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/58294/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 19:28:09  来源:igfitidea点击:

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

pythonsockets

提问by verix

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?

当我调用socket.getsockname()套接字对象时,它返回我机器的内部 IP 和端口的元组。但是,我想检索我的外部 IP。这样做最便宜、最有效的方式是什么?

采纳答案by John Millikin

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.

如果没有外部服务器的合作,这是不可能的,因为您和另一台计算机之间可能存在任意数量的 NAT。如果是自定义协议,您可以要求其他系统报告它连接到的地址。

回答by Cody Brocious

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.

我能想到的唯一方法就是使用http://whatismyip.com/ 之类的服务来获取它。

回答by Rafael Lopes

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

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

回答by Scott

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!

DuckDuckGo 的 IP 答案将以 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)

回答by Vasilii Pascal

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

回答by Vasilii Pascal

import socket

进口插座

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

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

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

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

s.getsockname()

s.getsockname()

回答by frankjania

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

使用http://whatismyip.com来源中建议的地址

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

回答by Ahmed



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

您需要连接到外部服务器并从响应中获取您的公共 IP



like this:

像这样

   import requests

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

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