Welcome aboard! We are happy you are here and wish you good net-raft!
<% @Page Language="C#" %>
<!-- code section -->
<script runat="server">
private void get_ip(object sender, EventArgs e)
{
System.Web.HttpContext context = System.Web.HttpContext.Current;
string ipAddress = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (!string.IsNullOrEmpty(ipAddress))
{
string[] addresses = ipAddress.Split(',');
if (addresses.Length != 0)
{
Response.Write(addresses[0]);
}
}
Response.Write(context.Request.ServerVariables["REMOTE_ADDR"]);
}
</script>
<html>
<head>
</head>
<body>
<form runat="server">
<input runat="server" id="button1" type="submit" value="get ip" OnServerClick="get_ip"/>
<hr />
</form>
</body>
</html>
// this is the complete solution, copy and use
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js "></script>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
url: "Default.aspx/DisplayData",
data: '{}',
dataType: "json",
success: function (data) {
$("#lbltxt").text(data.d);
},
error: function (result) {
alert("Error");
}
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<label id="lbltxt" runat="server"></label>
</div>
</form>
</body>
</html>
//copy inot Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using System.Web.Script.Serialization;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string DisplayData()
{
using (var webClient = new System.Net.WebClient()){
var data = webClient.DownloadString("https://geoip-db.com/json ");
JavaScriptSerializer jss = new JavaScriptSerializer();
var d = jss.Deserialize<dynamic>(data);
string ipv4 = d["IPv4"];
return "ip address: " + ipv4;
}
}
}
The most helpful C# solutions