简体   繁体   English

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

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

I am using this script to get User's Client IP: 我正在使用此脚本来获取用户的客户端IP:

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

I can get the IP using JavaScript as Geo.IP , but I need to get it in code behind on button click. 我可以使用JavaScript作为Geo.IP来获取IP,但是我需要在单击按钮时通过代码获取它。

Something like: 就像是:

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

    // IP = ???

    // Validation code

}

Any ideas? 有任何想法吗?

Thanks in advance... 提前致谢...

Why the client-side script? 为什么要使用客户端脚本? Request.UserHostAddress sounds like what you're looking for. Request.UserHostAddress听起来像您要找的东西。 :) :)

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

    // Validation code

}

If you really can't use server variables, or if you need the geo information as well as the IP, you'll need something like the following: 如果您确实无法使用服务器变量,或者您需要地理位置信息和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>

This puts the JSON equivalent of the Geo object in your geoiplookup reference 这会将与Geo对象等效的JSON放入您的geoiplookup参考中

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

into an ASP.NET hidden field. 进入ASP.NET隐藏字段。

Then, on the server, you can access it like: 然后,在服务器上,您可以像这样访问它:

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