How to get clients computer name using asp.net mvc? - c#

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()

Related

How to get the client's IP automatically in ASP.NET CORE

I want to find the user's IP without the user automatically submitting the request from the URL itself. When I do this locally, it returns the correct IP address, but when I publish the web service on the server, this IP becomes the server IP, what should I do?
For example, I have a service at the address https://test.com/api/GetAddress, I call this service in PostMan with the below code and it returns the user's IP address correctly, but when this service is on a site at the address https://sitetest.com/Dashboard/GetHome is called, the server address is returned and the user address is not given to me.
Note that I want to get this IP through the URL itself, because if I
put this in the Request and it is received through the developer, it
can give any IP to the Api.
I have used both types of code but still the same:
public static string GetClientIp()
{
try
{
string strHostName = System.Net.Dns.GetHostName();
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList
.FirstOrDefault(a => a.AddressFamily == AddressFamily.InterNetwork);
return ipAddress?.ToString();
}
catch (Exception ex)
{
return "0.0.0.0";
}
//return HttpContext.Current.Connection.RemoteIpAddress?.ToString() ?? "0.0.0.0";
}
Inside a controller get the client ip address using:
var address = Request.HttpContext.Connection.RemoteIpAddress;
If you are using a reverse proxy then you have to use the Forwarded Headers Middleware. Example:
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
});
This is because the proxy forwards the request to your app so RemoteIpAdress has the ip address of the machine where the proxy is running. Most proxies usually set X-Forwarded-For header with the originating ip address. This middleware reads X-Forwarded-For header and sets the RemoteIpAdress correctly.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For

How can I get a user's IP address in C#/asp.net/MVC 5?

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;
}

Get machine Public IP

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");

Get Hostname in WCF on IIS

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;

How to get the domain name/IP name in web-API?

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.

Categories