JavaScript 中获取 IP 地址的方法有两种:获取公共 IP 地址 (fetch('https://api.ipify.org?format=json')...) 和获取本地 IP 地址 (function getLocalIP() {...})。获取公共 IP 地址需要启用 CORS,而获取本地 IP 地址可能会因客户端禁用或浏览器出于隐私考虑阻止而失败。

获取 IP 地址的 JavaScript 方法
获取客户端的 IP 地址对于网络应用和分析至关重要。在 JavaScript 中,有几种方法可以实现此目的。
获取公共 IP 地址
要获取客户端的公共 IP 地址(即从互联网上可见的 IP 地址),可以使用以下代码:
<code class="javascript">fetch('https://api.ipify.org?format=json')
.then((res) => res.json())
.then((data) => console.log(data.ip))
.catch((error) => console.error(error));</code>获取本地 IP 地址
要获取客户端的本地 IP 地址(即在本地网络上可见的 IP 地址),可以使用以下代码:
<code class="javascript">function getLocalIP() {
const interfaces = require('os').networkInterfaces();
for (const name in interfaces) {
for (const address of interfaces[name]) {
if (
address.family === 'IPv4' &&
!address.internal &&
address.address !== '127.0.0.1'
) {
return address.address;
}
}
}
return undefined;
}</code>注意事项
fetch() API 获取公共 IP 地址需要启用 CORS。以上就是如何通过js获取ip的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号