How to get the public IP address of a user in C#
asp.net, asp.net-mvc, asp.net-mvc-4, c#
Solution
This is what I use:
protected void GetUser_IP()
{
string VisitorsIPAddr = string.Empty;
if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
{
VisitorsIPAddr = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
}
else if (HttpContext.Current.Request.UserHostAddress.Length != 0)
{
VisitorsIPAddr = HttpContext.Current.Request.UserHostAddress;
}
uip.Text = "Your IP is: " + VisitorsIPAddr;
}
"uip" is the name of the label in the aspx page that shows the user IP.
Problem
I want the public IP address of the client who is using my website. The code below is showing the local IP in the LAN, but I want the public IP of the client. ``` //get mac address NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); String sMacAddress = string.Empty; foreach (NetworkInterface adapter in nics) { if (sMacAddress == String.Empty)// only return MAC Address from first card { IPInterfaceProperties properties = adapter.GetIPProperties(); sMacAddress = adapter.GetPhysicalAddress().ToString(); } } // To Get IP Address string IPHost = Dns.GetHostName(); string IP = Dns.GetHostByName(IPHost).AddressList[0].ToString(); ``` Output: Ip Address : 192.168.1.7 Please help me to get the public IP address.