laspalmos laspalmos - 2 months ago 38
C# Question

How I can obtain client hostname, local computer name and user name in c# and asp.net

I have the IP address, but for some reason I can get the name resolve correctly to show local computer name. I try few things and all of them is showing the server hostname?

ipadd = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
IPAddress myIP = IPAddress.Parse(ipadd);
IPHostEntry GetIPHost = Dns.GetHostEntry(myIP);


//userhostname = System.Environment.MachineName;
//userhostname = Dns.GetHostName(); //Resolve ServerHostName not computer
//userhostname = HttpContext.Current.Request.UserHostName;
//userhostname = HttpContext.Current.Request.UserAgent;
userhostname = GetIPHost.HostName;


For user name I am tring to use

nametext = WindowsIdentity.GetCurrent().Name;
//Shows server name when deployed on server
//when debuging and running localy shows correctly current user logged in

//nametext = HttpContext.Current.Request.ServerVariables["LOGON_USER"];
// not returning anything


I switched authentication and no results

<authentication mode="Forms">
<authentication mode="Windows">

Answer

Use HttpRequest.UserHostAddress and HttpRequest.UserHostName for client IP and machine name.

Assuming you have authentication configured correctly, you can get the client user from IIdentity.Name.

In the context of a Page, you can use Request.UserHostAddress, Request.UserHostName and User.Identity.Name.