how can I get the client's computer name in a web application. The user in a network.
Regards
// Already tryed this option
string IP = System.Web.HttpContext.Current.Request.UserHostAddress;
string compName = DetermineCompName(IP);
System.Net.IPHostEntry teste = System.Net.Dns.GetHostEntry(IP);
ssresult = IP + " - " + teste.HostName;
// TODO: Write implementation for action
private static string DetermineCompName(string IP)
{
IPAddress myIP = IPAddress.Parse(IP);
IPHostEntry GetIPHost = Dns.GetHostEntry(myIP);
string[] compName = GetIPHost.HostName.ToString().Split('.');
return compName[0];
}
All of that, gives me only the IP :/
You can't do this in a way that is guaranteed to work.
The closest you will be able to get is to go down the route of doing a reverse dns lookup using System.Net.Dns.GetHostEntry which is what you have already tried.
The problem is that your machine has no way of knowing the hostname of a remote web client via its IP address alone (unless it is on the same subnet, in which case you may be able to retrieve it).
You have to fall back on your DNS infrastructure being able to map the IP back into a hostname [this is what nslookup does when you type in a hostname], and plenty of places just won't bother setting up reverse IP records.
Plus, often if they do, they won't match the hostname. It is quite common to see a reverse lookup for "1.2.3.4" come back as something line "machine-1.2.3.4", instead of the actual hostname.
This problem is exacerbated further if the clients are behind any sort of Network Address Translation so that many client computers have a single IP from an external perspective. This is probably not the case for you since you state "The user in a network".
As an aside, if you go to the server and type in, at a command prompt,
nslookup <some ip>
(where is an example of one of these client machines), do you get a hostname back?
If you do, then System.Net.Dns.GetHostEntry should be able to as well, if not then it probably can't for the reasons mentioned above.
you can get the windows machine name with - System.Environment.MachineName
Assuming your clients are Windows based running IE you could use this client side code to get the names and pass them back to the server:
<script type="text/javascript">
function create()
{
var net = new ActiveXObject("wscript.network");
document.write(net.ComputerName);
}
</script>
Yeah would require you to keep requesting and caching the computers terribly inefficient, was a bad idea.
I would go with running nslookup in the background I haven't tested this code and neither is it handling errors for failures, but basically, you can do:
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo sInfo = new System.Diagnostics.ProcessStartInfo("nslookup.exe", "192.168.1.100");
string result = process.StandardOutput.ReadToEnd();
Then just parse the result value.
Related
I can't find a question or post specific to Azure for this, and I'm not sure what's different in the environment in Azure versus my testing environments that would cause this.
I've tried a few methods to get this to work but I'm not coming right. Please note this isn't Webapi, so using the HttpRequestMessage, as far as I know, is not going to work either.
Here's what I've tried so far:
Method 1:
string ipAddress = "";
IPHostEntry Host = default(IPHostEntry);
Host = Dns.GetHostEntry(System.Environment.MachineName);
ipAddress = Host.AddressList.SingleOrDefault(x => x.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork).MapToIPv4().ToString();
Method 2:
string userIP = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(userIP))
{
userIP = Request.ServerVariables["REMOTE_ADDR"];
}
return userIP;
Thanks in advance.
Read the value transported in this header:
x-forwarded-for: "91.23.44.24:52623"
Note there's a source port number trailing the IP address, so parse accordingly.
Also, as #NicoD correctly points out, the header in question may contain an array of proxy servers the request traversed. For example:
x-forwarded-for: "91.23.44.24:52623, 91.23.44.155"
Syntax
X-Forwarded-For: <client>, <proxy1>, <proxy2>
<client> The client IP address
<proxy1>, <proxy2> If a request goes through multiple proxies, the IP addresses of each successive proxy is listed. This means, the right-most IP address is the IP address of the most recent proxy and the left-most IP address is the IP address of the originating client.
What about that glaring port number you ask?
From https://www.rfc-editor.org/rfc/rfc7239:
5.2. Forwarded For
[...] this parameter MAY instead contain an IP
address (and, potentially, a port number).
All client requests are terminated in the frontend layer and proxied via Application Request Routing to your web worker (hosting the MVC5 application).
My application is sending reports to another application (which maintains a database of reports) on the network with simple IPv4 addresses. I can construct a valid IPAddress in two ways:
string address = "200.1.2.41";
IPAddress ip1 = IPAddress.Parse(address);
IPAddress ip2 = (Dns.GetHostEntry(address)).AddressList[0];
If address represents an IP that is reachable, both methods are quick (though IPAddress.Parse is quickest). But if address is not reachable (eg. the server is off or the user has entered the wrong IP in Settings) then Parse is lightning quick...but Dns.GetHostEntry hangs for up to 9s.
I did a parameter-by-parameter check and the final variables ip1 and ip2 are identical. Given that Parse is always quick, and that I'm using standard four-octet IPv4 addresses only, is there any compelling reason to use the Dns.GetHostEntry method? Might I need Dns.GetHostEntry if I switch to IPv6 or named hosts like FOOD.HALL.01 in future?
If you just want get an instance of IPAddress for your IP address string representation, than yes, using the DNS for that purpose is absolute overkill.
All sorts of timeouts, latencies, etc. are absolute expected. At least compared to the purely local parsing and disecting of the string representation that happens in IPAddress.Parse(). What that does is, ask the DNS server to resolve the IP address string into a hostname "entry". From that you get the IP address back that you knew all along (albeit as string and not IPAddress).
Now, if you want to be able to "convert" host names into IP addresses in the future, then yes, you need to go via DNS.
But you could always do it in that manner (conceptually):
// First see if it is a valid IP address rep - fast.
IPAddress ip;
if (!IPAddress.TryParse(address, out ip))
{
// See if it is a hostname - slower.
ip = Dns.GetHostEntry(address).AddressList[0];
}
And yes, IPAddress.TryParse() (or Parse()) can handle IPv4 and IPv6 addresses.
I think I may be in a situation where the answer is this is not possible but in case not here goes...
I have written an ASP .NET MVC 3 application and I am using the Request.UserHostName property and then passing the value that that returns into Dns.GetHostEntry to find out all the possible IPs and the host name for the currently connected client, for example:
var clientAddress = Request.UserHostName;
var entry = Dns.GetHostEntry(clientAddress);
Generally that is fine except I have a case where I get a "host not found" SocketException from the Dns.GetHostEntry call.
The really odd thing is that the address that is returned from the Request.UserHostName property is not the public address or any of the private addresses. To prove this I ran this bit of code on the client machine in question...
var host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var a in host.Aliases)
{
Console.WriteLine("alias '{0}'", a);
}
foreach (var a in host.AddressList)
{
Console.WriteLine("ip address '{0}'", a);
}
// ...from http://stackoverflow.com/a/2353177/1039947...
String direction = "";
WebRequest request = WebRequest.Create("http://checkip.dyndns.org/");
using (WebResponse response = request.GetResponse())
{
using (var stream = new StreamReader(response.GetResponseStream()))
{
direction = stream.ReadToEnd();
}
}
int first = direction.IndexOf("Address: ") + 9;
int last = direction.LastIndexOf("</body>");
direction = direction.Substring(first, last - first);
Console.WriteLine("Public IP: '{0}'", direction);
It prints three IP addresses (::1, one private and one public) but none of them are the address that is returned from Request.UserHostName.
If I pass in any of the addresses printed from the above test application into the Dns.GetHostEntry method I get a sensible value back.
So, is there any way that I could get from this strange IP address that is not the public nor any of the privates, to one where I could get the host entry for it without an exception (and what is this address)?
By the way, there is no X_FORWARD_FOR header or anything else that I may be able to identify the client with, as far as I can tell, in the HTTP message?
Background to the Question
So it was pointed out (thanks Damien) that if I explained why I am asking this perhaps someone can provide an alternative approach so here is some background...
I have a requirement that the administrator of the application should be allowed to specify in the configuration a single machine that is allowed to view the page - IP address or machine name - I can probably get the machine name requirement removed but even if they specify the IP address in the configuration it will still not match the IP address that is returned from the UserHostName property since they will use the IP address that is returned when they ping the machine name.
My thinking, therefore, was that if I take whatever is sent in the HTTP header and pass that into GetHostEntry then take all the possible results from that (all the IPs and the host name) and see if any of them match the configured value I could say "allow" otherwise "disallow" (I was going to remove the part of the host name before the first dot too, to cover that eventuality). That scheme has been blown out of the water by this situation I have where the IP address is not at all what I would expect.
The host name of the client is not normally known because it is not transmitted at the HTTP level. The server cannot know it. Look at the HTTP requests with Fiddler to see for yourself that there is not a lot of information available to the server (and the client can forge all request contents of course).
Use the UserHostAddress property to get the IP address. That is the most you can reliably find out. Once you have that you can try to reverse the IP to a host name but that is not always possible.
I have a more specific answer to your question. By examining the source code for HttpRequest.UserHostName here, I found that it maps to a IIS server variable named REMOTE_HOST which is described here. The property will return the IP adddress of the client, unless you have configured IIS in the way described, in which case IIS will do a reverse DNS lookup to attempt to return the name associated with the IP.
Make sure you read the Remarks section at Dns.GetHostEntry on the many cases it can (partially) fail:
Remarks
The GetHostEntry method queries a DNS server for the IP
address that is associated with a host name or IP address.
If an empty string is passed as the hostNameOrAddress argument, then this method
returns the IPv4 and IPv6 addresses of the local host.
If the host name could not be found, the SocketException exception is returned
with a value of 11001 (Windows Sockets error WSAHOST_NOT_FOUND). This
exception can be returned if the DNS server does not respond. This
exception can also be returned if the name is not an official host
name or alias, or it cannot be found in the database(s) being queried.
The ArgumentException exception is also returned if the
hostNameOrAddress parameter contains Any or IPv6Any.
The GetHostEntry method assumes that if an IP literal string is passed in the
hostNameOrAddress parameter that the application wants an IPHostEntry
instance returned with all of the properties set. These properties
include the AddressList, Aliases, and HostName. As a result, the
implementation of the GetHostEntry method exhibits the following
behavior when an IP string literal is passed:
The method tries to parse the address. If the hostNameOrAddress parameter contains a legal IP string literal, then the first phase succeeds.
A reverse lookup using the IP address of the IP string literal is attempted to obtain the host name. This result is set as the HostName property.
The host name from this reverse lookup is used again to obtain all the possible
IP addresses associated with the name and set as the AddressList
property.
For an IPv4 string literal, all three steps above may
succeed. But it is possible for a stale DNS record for an IPv4 address
that actually belongs to a different host to be returned. This may
cause step #3 to fail and throw an exception (there is a DNS PTR
record for the IPv4 address, but no DNS A record for the IPv4
address).
For IPv6, step #2 above may fail, since most IPv6
deployments do not register the reverse (PTR) record for an IPv6
address. So this method may return the string IPv6 literal as the
fully-qualified domain (FQDN) host name in the HostName property.
The GetHostAddresses method has different behavior with respect to IP
literals. If step #1 above succeeds (it successfully parses as an IP
address), that address is immediately returned as the result. There is
no attempt at a reverse lookup.
IPv6 addresses are filtered from the results of the GetHostEntry method if the local computer does not have IPv6 installed. As a result, it is possible to get back an empty
IPHostEntry instance if only IPv6 results where available for the
hostNameOrAddress.parameter.
The Aliases property of the IPHostEntry instance returned is not populated by this method and will always be empty.
I am building an intranet site that will display different lists based on the computer name because different computers are in different areas, is there a way (within a controller or model) to determine the client's computer name?
I have tried system.environment.machinename but that only returns the name of the server, any other ideas?
I got it working using the following:
string IP = Request.UserHostName;
string compName = CompNameHelper.DetermineCompName(IP);
code from compnamehelper:
public static string DetermineCompName(string IP)
{
IPAddress myIP = IPAddress.Parse(IP);
IPHostEntry GetIPHost = Dns.GetHostEntry(myIP);
List<string> compName = GetIPHost.HostName.ToString().Split('.').ToList();
return compName.First();
}
code in VB :
Dim myIP As IPAddress = IPAddress.Parse(Request.UserHostName)
Dim GetIPHost As IPHostEntry = Dns.GetHostEntry(myIP)
Dim compName As List(Of String) = GetIPHost.HostName.ToString.Split("").ToList
return(compName.First)
No. The client's computer name is not available in any way on the server. This is the nature of the http request-response. You only can have its IP address.
A workarounds could be to retrieve machine on the client from Flash/Silverlight (I doubt JavaScript) and put in into cookie which is available on the server with each request. But there is a whole stack of issues with this approach.
I think you are better off using one of these methods to tie a user to a location:
a cookie that is set once the user self-selects their location
having the user login to the site so that you can track them uniquely that way
remembering user by IP address
There is no way of ensuring remote hostnames are unique. The same issue occurs with IP because of proxies, dynamic IP, etc., but I think it will be a little more reliable. Also, you can do geolocation by IP address.
Try this:
string name = Request.UserHostName;
The only way I know of to inspect the client is through the ServerVariables collection on the Request object (should be available for MVC code).
See https://web.archive.org/web/20210927201638/http://www.4guysfromrolla.com/webtech/092298-3.shtml for more information. REMOTE_HOST and REMOTE_ADDR look like candidates.
Here's an IE-only solution. It works in IE8, with multiple security warnings.
<script type="text/javascript" language="javascript">
var ax = new ActiveXObject("WScript.Network");
document.write(ax.UserName + '<br />'); //logged in account name
document.write(ax.ComputerName + '<br />'); //Windows PC name
</script>
How do you get the ipaddress and location of every website vistor of your website through Asp.Net?
Thanks
To get the user's IP use:
Request.UserHostAddress
You can use this webservice to get their geographic location.
http://iplocationtools.com/ip_location_api.php
string VisitorIPAddress = Request.UserHostAddress.ToString();
and based on the ipaddress you can narrow down the location: find the geographical location of a host
Request.UserHostAddress won’t work if you're behind a proxy. Use this code:
public static String GetIPAddress()
{
String ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(ip))
ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
else
ip = ip.Split(',')[0];
return ip;
}
Note that HTTP_X_FORWARDED_FOR should be used BUT as it can return multiple IP addresses separated by a comma you need to use the Split function. See this page for more info.
Well the following property should give you the IP Address of teh client (or the clients proxy server)
Request.UserHostAddress
As for location, you'd need to use some GeoIP/GeoLocation plugin like MaxMind to figure that out.
http://www.maxmind.com/
To get the IP do:
Request.UserHostAddress
And you can map IP to location using a webservice (slower) or a database (faster) like this:
http://ip-to-country.webhosting.info/node/view/5
It's server technology-agnostic, but I'd recommend piggy-backing on Google's AJAX loader: http://code.google.com/apis/ajax/documentation/#ClientLocation
It's in Javascript and will even give you the person's city/state/country (well, it takes a guess based on IP address). Post it back to the server and it's available to you in ASP.NET or whatever.