繁体   English   中英

如何通过背后的代码从第三方获取用户的客户端IP

[英]How to get user's client IP from a third party from code behind

我正在使用此脚本来获取用户的客户端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

}

有任何想法吗?

提前致谢...

为什么要使用客户端脚本? 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放入您的geoiplookup参考中

{"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"];
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM