Trying to get the public address(not local IP) of the machine using c#. Unable to get Public IP.
We can get public IP Address using external libraries or API like in this link.
Is there any possible to get machine pubic IP address in c# without using external API and libraries?
Try this
public String getPublicIp()
{
HTTPGet req = new HTTPGet();
req.Request("http://checkip.dyndns.org");
string[] a = req.ResponseBody.Split(':');
string a2 = a[1].Substring(1);
string[] a3=a2.Split('<');
string ip = a3[0];
return ip;
}
Retrieve public IP (V4) address, asynchronously (recommended)
HttpClient client = new HttpClient();
var ipTask = client.GetStringAsync("https://api.ipify.org");
var ipAddress = await ipTask;
For IP V6, use this URL:
var ipTask = client.GetStringAsync("https://api6.ipify.org");
Related
The following code works OK locally, but it will only get the server's IP (if I'm correct).
try
{
string externalIP;
externalIP = (new WebClient()).DownloadString("http://checkip.dyndns.org/");
externalIP = (new Regex(#"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"))
.Matches(externalIP)[0].ToString();
model.IpCreacion = externalIP;
}
catch { }
I can't test this right now, because the two guys at my office that can make this as a public URL for testing on a server aren't here today. The code is in the controller of the project, so it runs on the server every time a client executes the app, it's not actually the client who is getting the IP address.
How can I make the client get his IP address, instead of the server, executing the code I just showed?
If I managed to put this functionality in a view, would it work as I'm intending to?
UPDATE: I tried other methods posted as answers, like
string ip = System.Web.HttpContext.Current.Request.UserHostAddress;
and
model.IpCreacion = null;
model.IpCreacion = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(model.IpCreacion))
{
model.IpCreacion = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
but now I'm only getting ::1 as a result. Which didn't happen before, as I was getting a correct IP address.
if you want to get client ip address,visit bellow post in stackoverflow
How can I get the client's IP address in ASP.NET MVC?
That gets only IP of server, because you send the request from Web Server to checkip.dyndns.org.
To get the client IP, you need to use JavaScript and do the same thing.
$.get('http://checkip.dyndns.org/', function(data) {
console.log(data); // client IP here.
})
UPDATED:
If you need client IP Address in ASP.NET Core, you can inject this service
private IHttpContextAccessor _accessor;
And use it as
_accessor.HttpContext.Connection.RemoteIpAddress.ToString()
Or in ASP.NET Framework
Public string GetIp()
{
string ip = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(ip))
{
ip = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
return ip;
}
Public string GetIp()
{
string ip = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(ip))
{
ip = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
return ip;
}
I am supporting a system that needs to get the client's computer name I try different codes but all of them just get the computer name of the host server, not the client's computer name. Here's the snippet:
public void CreateEvents(string className, string eventName, string eventData, string userId)
{
string hostName = Dns.GetHostName(); // Retrive the Name of HOST
string compname= HttpContext.Current.Request.UserHostAddress;
var browser = HttpContext.Current.Request.Browser.Browser + " " + HttpContext.Current.Request.Browser.Version;
if (string.IsNullOrEmpty(userId))
{
userId = compname;
}
var entity = new EventLog
{
ClassName = className,
EventName = eventName,
EventData = eventData,
IpAddress = ipAddress,
Browser = browser,
UserId = userId,
CreatedDate = DateTime.Now
};
_db.EventLogs.Add(entity);
_db.SaveChanges();
}
public string GetIpAddress()
{
HttpContext context = System.Web.HttpContext.Current;
string compname= context.Request.UserHostAddress; //System.Net.Dns.GetHostName();
return compname;
}
Thanks in advance!
No you can't, unless the client sends such info when making HTTP requests. By "client", I'm referring to any - some app, browser, etc.
You can inspect your own browser request flow using standard browser dev tools and see exactly what info your browser is sending. It will not have your machine name (unless something in your machine is and that would likely be a problem).
That said, HTTP Header data is what you have aside from standard network info such as IP address (which also isn't guaranteed to be the client's IP address - it could be the client's network address). The closest you can get to is hostname if it exists, and even then, just like IP address, is not guaranteed to be machine name.
A possible exception would be in an internal network (LAN).
you can use
HttpContext.Request.UserHostAddress
for getting the IP address, also Request has UserHostName but I am not sure about this property
You can get computer name as follows:
Environment.MachineName.ToString()
You can get hosting server name as follows:
Server.MachineName.ToString()
Based on below pic, there may be several WebSite on IIS with several services,
So the only thing which I have separate them from together is Hostname , in the other site sibling services may call together so I have decided to change hostname if they are not on localhost so in service I tried something like this:
HostName = OperationContext.Current.Channel.LocalAddress.Uri.Host.ToString();
and in service when I am calling another service by it's proxy I Rehome
public void ReHome(string hostName)
{
if (!string.IsNullOrEmpty(hostName))
{
if (this.Endpoint.Address.Uri.DnsSafeHost.ToLower().Equals("localhost"))
{
string newAddress = string.Format("{0}://{1}{2}/{3}", Endpoint.Address.Uri.Scheme
, hostName, string.IsNullOrEmpty(Endpoint.Address.Uri.Port.ToString()) ? string.Empty : ":" + Endpoint.Address.Uri.Port.ToString()
, Endpoint.Address.Uri.AbsolutePath);
this.Endpoint.Address = new EndpointAddress(newAddress);
}
}
}
call example in a service:
using (var hisProxy = new HISIntegrationClient("hisIntegrationEndPoint", Internals.SYSTEM))
{
hisProxy.ReHome(HostName);
....
}
so is OperationContext.Current.Channel.LocalAddress.Uri.Host give me what I want that mentioned in above pic?
You get the current base address of server(hostname and port) using following code snippet
var baseAddress = OperationContext.Current.Host.BaseAddresses[0].Authority;
I want Client machine internet IP Address in asp.net web service for that I am using following code
string IPaddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(IPaddress))
IPaddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
if (string.IsNullOrEmpty(IPaddress))
IPaddress = HttpContext.Current.Request.UserHostAddress;
but Here I am getting the client machine local IP But * I am looking public IP/ Internet IP of the client machine*
Please Help me, anybody.
There are couple of attributes of Request which provides client IP address.
Here is the code:
private string GetClientIpAddress (HttpRequestMessage request)
{
if ( request.Properties.ContainsKey("MS_HttpContext") )
{
return ((HttpContextWrapper) request.Properties["MS_HttpContext"]).Request.UserHostAddress;
}
if ( request.Properties.ContainsKey(RemoteEndpointMessageProperty.Name) )
{
var prop = (RemoteEndpointMessageProperty) request.Properties[RemoteEndpointMessageProperty.Name];
return prop.Address;
}
if ( request.Headers.Contains("X-Forwarded-For") )
{
return request.Headers.GetValues("X-Forwarded-For").FirstOrDefault();
}
// Self-hosting using Owin. Add below code if you are using Owin communication listener
if ( request.Properties.ContainsKey("MS_OwinContext") )
{
var owinContext = (OwinContext) request.Properties["MS_OwinContext"];
if ( owinContext?.Request != null )
{
return owinContext.Request.RemoteIpAddress;
}
}
if ( HttpContext.Current != null )
{
return HttpContext.Current.Request.UserHostAddress;
}
return null;
}
Hope it will work.
~Prasad
You get the IP address of the connection by which the client is connecting to your server. If this is within the same network, you won't see a public IP address, because the connection is not routed over the internet.
How can I get the (ipName:PortNumber) mentioned in the below IP address in web-API?
https://**ipName:PortNumber**/ProductController/{productId}
We have diff servers such as: 000.00.000:8080 (ipname:portnumber), 111.11.111:8181.
I want to load these dynamically into a string as shown below.
string webServiceUrl = "https://"+ IP name +"Product Controller/{product Id}"
If you have your URI in a string, you can get the information you want as follows:
Uri uri = new Uri("https://example.com:1234/ProductController/7");
string host = uri.Host; // "example.com"
int port = uri.Port; // 1234
Inside of an ApiController, you can get the current request's URI as Request.RequestUri.
If you want to construct a URI given the host and port, you can simply do something lightweight like this:
string uri = string.Format("https://{0}:{1}/ProductController/7", host, port);
Or something a little more robust like use the UriBuilder class.
Here's how I access the Request object within a Web Api...
if (Request.Properties.ContainsKey("MS_HttpContext"))
{
var ip = (HttpContextWrapper)Request.Properties["MS_HttpContext"]).Request.UserHostAddress;
var host = ((HttpContextWrapper)Request.Properties["MS_HttpContext"]).Request.Url.Host;
var port = ((HttpContextWrapper)Request.Properties["MS_HttpContext"]).Request.Url.Port;
}
Hope it helps.