检索客户端请求 IP 地址



这篇文章不再是一个问题;我只是想发布这个来帮助其他人将来避免浪费时间。

目标: 检索客户端 IP 地址,并根据 IP 中的某个八位字节设置一些特定值。

我正在为我的公司开发一个反应网络应用程序,需要支持三个设施。当然,这三个位置存在于不同的地理区域,并且IP模式略有不同。

我需要根据客户端 IP 中的八位字节值设置一些会话标识符。为此,我执行了以下步骤。

  1. 设置快速路线,让用户在首次访问应用程序时点击。
  2. 获取客户端 IP 并存储在 const/var 中。
  3. "."分解 IP 字符串。
  4. 执行If/ThenSwitch以确定所需八位字节的值。
  5. 在匹配条件下设置一些会话/逻辑。

由于 express,req对象包含一个带有请求 IP 地址值的 ip 密钥。我们可以利用这个或其他第三方库来获取所需的信息。当然,有更好/更安全的方法可以做到这一点,但这是我研究和设置的简单方法。绝对感谢社区帮助我解决这个问题。

apiRouter.route('/test')
.get((req, res) => {
const request_ip = req.ip;      // Returns string like ::ffff:192.168.0.1
const ip_array = request_ip.split('.')      // Returns array of the string above separated by ".". ["::ffff:192","168","0","1"]
// The switch statement checks the value of the array above for the index of 2. This would be "0"
switch(ip_array[2]) {
case('0'):
res.json({'request-ip':ip_array, 'location':'Location A'});
break;
case('1'):
res.json({'request-ip':ip_array, 'location':'Location B'});
break;
case('2'):
res.json({'request-ip':ip_array, 'location':'Location C'});
break;
default:
res.json({'request-ip':ip_array, 'location':'Default Location'});
}
})

我的主要问题之一是我在本地笔记本电脑上开发。我的节点服务器在这里运行快速。我还试图从本地机器获取我的请求 ip。这没有意义,因为我不断"::1"作为我的请求 IP 返回。困惑的是,我做了很多研究,最终发现这是一个明显的PEBKAC问题。感谢这篇文章中的 nikoss,它使世界上所有的事情都有意义。

您可以通过从开放 IP 获取此信息来获取此信息

https://api.ipdata.co/

fetch("https://api.ipdata.co")
.then(response => {
return response.json();
}, "jsonp")
.then(res => {
console.log(res.ip)
})
.catch(err => console.log(err))

这行得通!

async componentDidMount() {

const response = await fetch('https://geolocation-db.com/json/');
const data = await response.json();
this.setState({ ip: data.IPv4 })
alert(this.state.ip)
}

在 JSX 中将其用作

{this.state.ip}

似乎 https://api.ipdata.co 不再起作用,即使指定了键。我最终使用了Ipify(打字稿):

private getMyIp() {
fetch('https://api.ipify.org?format=json').then(response => {
return response.json();
}).then((res: any) => {
this.myIp = _.get(res, 'ip');
}).catch((err: any) => console.error('Problem fetching my IP', err))
}

这是替代IP检索服务的良好参考:https://ourcodeworld.com/articles/read/257/how-to-get-the-client-ip-address-with-javascript-only

如果https://api.ipdata.co不起作用,您可以使用geolocation-db.com/json.地理位置的优势 它还为您提供其他重要值,例如latitude, longitude, country, state, zip

fetch(`https://geolocation-db.com/json/`)
.then(res => res.json())

您可以console.log(...)res.json()以查看 JSON 值。

你也可以使用这个。

fetch('https://get-ip-only.herokuapp.com/') .then(r => r.json()) .then(resp => console.log(resp.ip))

https://get-ip-only.herokuapp.com/此 API 仅提供 IP。

最新更新