当我打电话时 socket.getsockname() 在套接字对象上,它返回我的机器的内部 IP 和端口的元组。但是,我想找回我的外部IP。最便宜、最有效的方式是什么?

有帮助吗?

解决方案

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

其他提示

我能想到的唯一能保证给你的方法就是使用类似的服务 http://whatismyip.com/ 为拿到它,为实现它。

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

进口插座

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

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

s.getsockname()

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

您需要使用外部系统来执行此操作。

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)

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

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

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


像这样:

   import requests

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

   print("\n[+] My Public IP: "+ myPublic_IP+"\n")
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top