Reputation: 4051
I am using this script to get User's Client 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.
Something like:
protected void Button1_Click(object sender, EventArgs e)
{
string IP = string.Empty;
// IP = ???
// Validation code
}
Any ideas?
Thanks in advance...
Upvotes: 1
Views: 388
Reputation: 50104
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:
<!-- 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
{"city":"London","country":"GB","lat":"51.514198","lon":"-0.093100",
"IP":"193.129.26.250","netmask":"24"}
into an ASP.NET hidden field.
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"];
}
Upvotes: 0
Reputation: 12419
Why the client-side script? Request.UserHostAddress sounds like what you're looking for. :)
protected void Button1_Click(object sender, EventArgs e)
{
string IP = Request.UserHostAddress;
// Validation code
}
Upvotes: 1