【发布时间】:2008-09-12 04:21:51
【问题描述】:
当我在套接字对象上调用socket.getsockname() 时,它会返回我机器的内部IP 和端口的元组。但是,我想检索我的外部 IP。这样做最便宜、最有效的方式是什么?
【问题讨论】:
-
另一个提供简洁解决方案的优秀网站是从icanhazip.com获取HTTP请求
当我在套接字对象上调用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()
【讨论】:
https://jsonip.com/(永久为 301)。顺便提一句。对我来说,它完美无缺。就我而言,响应中的外部 IP 是 IPv6 格式,这很好。不错。
您需要使用外部系统来执行此操作。
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)
【讨论】:
导入套接字
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())
【讨论】:
获取公网IP最简单的方法就是使用这个
import requests
IP = requests.get('https://api.ipify.org/').text
print(f'Your IP is: {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")
【讨论】: