如何从代码隐藏的第三方获取用户的客户端IP

时间:2013-02-12 08:01:37

标签: c# javascript asp.net

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

}

有什么想法吗?

提前致谢...

2 个答案:

答案 0 :(得分:1)

为什么是客户端脚本? Request.UserHostAddress听起来像你正在寻找的。 :)

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

    // Validation code

}

答案 1 :(得分:0)

如果确实无法使用服务器变量,或者您需要地理信息以及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"];
}