XMLHttpRequest
對(duì)象或fetch
API發(fā)起請(qǐng)求,然后從響應(yīng)頭中獲取服務(wù)器的IP地址。
在JavaScript中,可以通過以下方法獲取服務(wù)器IP地址:
1、使用fetch
API向一個(gè)返回服務(wù)器IP地址的API發(fā)起請(qǐng)求。
2、使用XMLHttpRequest
對(duì)象發(fā)起請(qǐng)求。
3、使用navigator.connection.effectiveType
屬性獲取網(wǎng)絡(luò)類型。
4、使用navigator.connection.rtt
屬性獲取往返時(shí)間。
5、使用window.location.hostname
獲取主機(jī)名。
6、使用window.location.host
獲取主機(jī)名和端口號(hào)。
7、使用window.location.protocol
獲取協(xié)議。
8、使用window.location.port
獲取端口號(hào)。
9、使用window.location.pathname
獲取路徑名。
10、使用window.location.search
獲取查詢字符串。
以下是一個(gè)簡(jiǎn)單的示例,使用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); });
注意:這個(gè)方法依賴于外部API,可能會(huì)受到網(wǎng)絡(luò)狀況的影響。