Click here to Skip to main content
15,892,927 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
I want the client public ip in c# i have used the below code get the public ip of client but code is getting only hosted server IP only not getting client's public ip how to get the Public ip of client.


these code getting only hosted server ip.


What I have tried:

static string GetIPAddress()  
{  
    String address = "";  
    WebRequest request = WebRequest.Create("http://checkip.dyndns.org/");  
    using (WebResponse response = request.GetResponse())  
     using (StreamReader stream = new StreamReader(response.GetResponseStream()))  
     {  
        address = stream.ReadToEnd();  
     }  
  
     int first = address.IndexOf("Address: ") + 9;  
     int last = address.LastIndexOf("</body>");  
     address = address.Substring(first, last - first);  
  
     return address;  
}  


public string GetIPAddress()
{
try
{
// string address;
address = (new
WebClient()).DownloadString("http://checkip.dyndns.org/");
address = (new Regex(@"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"))
.Matches(address)[0].ToString();
return address;
}
catch { return null; }
}
Posted
Updated 9-Jun-18 1:20am

The request to the CheckIP service is executed on your server. In that case your server is the client for which the IP address is returned.

Note also that such services are only useful when behind a router that performs network translations. Otherwise, the IP is the same as for the local network interface.

If you want to get the IP address of a connected client on a server, just get that information from the socket using the Socket.RemoteEndPoint Property (System.Net.Sockets)[^].
 
Share this answer
 
 
Share this answer
 
A quick google will have revealed that this is a very frequently asked question and the answer never changes...what you want to do isn't possible due to the way the internet works.
 
Share this answer
 
Comments
Richard Deeming 9-Jun-18 10:52am    
Getting the local IP address isn't possible, and the information would be useless even if you could.

Getting the public IP address that the request originated from is possible, although it only identifies the network, not the computer.

The question isn't entirely clear, but I'm assuming "public IP of client" means the OP is looking for the public IP address of the network the request originated from.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900