
實時航班追蹤背后的技術:在線飛機追蹤器的工作原理
"ip": "123.45.67.89",
"city": "Beijing",
"region": "Beijing",
"country": "CN",
"loc": "39.9042,116.4074",
"org": "AS12345 Example ISP",
"timezone": "Asia/Shanghai"
}
curl http://ip-api.com/json
返回結果示例:
{
"status": "success",
"country": "China",
"countryCode": "CN",
"region": "BJ",
"regionName": "Beijing",
"city": "Beijing",
"zip": "",
"lat": 39.9042,
"lon": 116.4074,
"timezone": "Asia/Shanghai",
"isp": "Example ISP",
"org": "",
"as": "AS12345 Example ISP",
"query": "123.45.67.89"
}
這些接口簡單易用,適合快速獲取IP地址及相關信息。需要注意的是,部分API可能有調用頻率限制,需根據實際情況選擇合適的服務。
在Linux或macOS系統中,可以通過命令行工具查看當前IP地址。
curl
命令curl ifconfig.me
該命令會直接返回當前公網IP地址。
dig
命令dig +short myip.opendns.com @resolver1.opendns.com
該命令通過OpenDNS服務器查詢當前IP地址。
hostname
命令hostname -I
該命令會返回當前設備的所有IP地址(包括內網IP)。
ip
命令ip addr show
該命令會顯示網絡接口的詳細信息,包括IP地址、子網掩碼等。
如果你需要在程序中動態獲取IP地址,可以使用以下方法。
import requests
def get_public_ip():
response = requests.get('https://api.ipify.org?format=json')
ip_data = response.json()
return ip_data['ip']
print("當前IP地址:", get_public_ip())
const axios = require('axios');
async function getPublicIp() {
const response = await axios.get('https://api.ipify.org?format=json');
return response.data.ip;
}
getPublicIp().then(ip => console.log("當前IP地址:", ip));
這些代碼通過調用第三方API接口獲取當前IP地址,適合在開發中使用。
在Web開發中,可以通過JavaScript獲取用戶的IP地址。
fetch('https://api.ipify.org?format=json')
.then(response => response.json())
.then(data => {
console.log("當前IP地址:", data.ip);
});
該方法適合在前端頁面中獲取用戶的IP地址。需要注意的是,由于瀏覽器的安全限制,某些情況下可能無法直接獲取IP地址。
在服務器端(如Nginx、Apache或后端框架),可以通過以下方式獲取客戶端的IP地址。
在Nginx配置文件中,添加以下內容:
server {
listen 80;
server_name example.com;
location / {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_pass http://backend;
}
}
在后端代碼中,可以通過X-Real-IP
或X-Forwarded-For
頭獲取客戶端IP地址。
from flask import Flask, request
app = Flask(__name__)
@app.route('/')
def index():
client_ip = request.headers.get('X-Real-IP') or request.remote_addr
return f"客戶端IP地址:{client_ip}"
if __name__ == '__main__':
app.run()
X-Forwarded-For
頭獲取真實IP地址。查看當前IP地址的接口方法多種多樣,可以根據具體需求選擇合適的方式。無論是通過公共API、命令行工具,還是編程語言和服務器端配置,都能輕松實現IP地址的獲取。在實際應用中,建議結合隱私保護和安全性考慮,選擇合適的方案。