Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the public IP address of a user in C#

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.

like image 798
Neeraj Mehta Avatar asked Oct 10 '13 02:10

Neeraj Mehta


People also ask

How do I find my public IP address using cmd?

Open the command prompt: if you have a Start menu in your Windows system, open it and type cmd into the search bar. If you don't have a search bar, click Run instead. Type ipconfig into the command prompt (or the Run box). Find your IP address within the text that pops up.

How do I find public IP address programmatically?

you need to create a function in Activity. class file, and need to request a url that will give your public IP in text form: "https://api.ipify.org/. Click to open. Add this function call in your onCreate() function.

Which function would you use to find the IP address of a machine in C?

Here is a simple method to find hostname and IP address using C program. gethostname() : The gethostname function retrieves the standard host name for the local computer. gethostbyname() : The gethostbyname function retrieves host information corresponding to a host name from a host database.


1 Answers

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.

like image 167
FeliceM Avatar answered Oct 06 '22 00:10

FeliceM