XMLHttpRequest
對象或fetch
API發(fā)起請求,然后從響應(yīng)頭中獲取服務(wù)器的IP地址。
在JavaScript中,可以通過以下方法獲取服務(wù)器IP地址:
1、使用fetch
API向一個返回服務(wù)器IP地址的API發(fā)起請求。
2、使用XMLHttpRequest
對象發(fā)起請求。
3、使用navigator.connection.effectiveType
屬性獲取網(wǎng)絡(luò)類型。
4、使用navigator.connection.rtt
屬性獲取往返時間。
5、使用window.location.hostname
獲取主機名。
6、使用window.location.host
獲取主機名和端口號。
7、使用window.location.protocol
獲取協(xié)議。
8、使用window.location.port
獲取端口號。
9、使用window.location.pathname
獲取路徑名。
10、使用window.location.search
獲取查詢字符串。
以下是一個簡單的示例,使用fetch
API獲取服務(wù)器IP地址:
async function getServerIP() { try { const response = await fetch('https://api.ipify.org?format=json'); const data = await response.json(); return data.ip; } catch (error) { console.error('Error fetching server IP:', error); return null; } } getServerIP().then(ip => { console.log('Server IP:', ip); });
注意:這個方法依賴于外部API,可能會受到網(wǎng)絡(luò)狀況的影響。