如何获得用户';s来自代码背后第三方的客户端IP

本文关键字:背后 代码 第三方 IP 客户端 用户 何获得 | 更新日期: 2023-09-27 17:58:42

我正在使用此脚本获取用户的客户端IP:

<script type="text/javascript" src="http://geoiplookup.wikimedia.org/"></script>

我可以使用JavaScript作为Geo.IP来获取IP,但我需要在点击按钮后的代码中获取它。

类似于:

protected void Button1_Click(object sender, EventArgs e)
{
    string IP = string.Empty;
    // IP = ???
    // Validation code
}

有什么想法吗?

提前感谢。。。

如何获得用户';s来自代码背后第三方的客户端IP

为什么使用客户端脚本?Request.UserHostAddress听起来像您要查找的地址。:)

protected void Button1_Click(object sender, EventArgs e)
{
    string IP = Request.UserHostAddress;
    // Validation code
}

如果真的不能使用服务器变量,或者如果你需要地理信息和IP,你需要以下内容:

<!-- Get geo information -->
<script type="text/javascript"
    src="http://geoiplookup.wikimedia.org/">
</script>
<!-- JavaScript object-to-JSON -->
<!-- Don't actually hotlink this; host it yourself -->
<script type="text/javascript" 
    src="https://github.com/douglascrockford/JSON-js/blob/master/json2.js">
</script>
<!-- Hidden field to hold result -->
<asp:HiddenField id="hdnGeo" runat="server"></asp:HiddenField>
<!-- Script to populate field -->
<script type="text/javascript">
    document.getElementById('<%= hdnGeo.ClientID %>').value =
        JSON.stringify(Geo);
</script>

这将Geo对象的JSON等价物放入geoiplokup引用中

{"city":"London","country":"GB","lat":"51.514198","lon":"-0.093100",
 "IP":"193.129.26.250","netmask":"24"}

转换为ASP.NET隐藏字段。

然后,在服务器上,您可以访问它,如:

protected void Button1_Click(object sender, EventArgs e)
{
    string json = hdnGeo.Value;
    var dictionary = new JavaScriptSerializer()
        .Deserialize<Dictionary<string, string>>(json);
    string city = dictionary["city"];
    string lat = dictionary["lat"];
    string lon = dictionary["lon"];
    string IP = dictionary["IP"];
    string netmask = dictionary["netmask"];
}