Got an asp.net web page in c#. One thing we would like to do is track hits to the site including their IP address. I implemented some code (thanks to SO) but the logged IP address always seem to be local, ie: 192.168.x.x. I have tried it from a variety of devices, even my phone and Version MiFi just to make sure its not something weird with the ISP but the log always list the same 2-3 different internal ip addresses (seems to change a little as the day goes on).
Here is my function that gets the IP (again thanks to postings here on SO):
protected IPAddress GetIp(HttpRequest request)
{
string ipString;
if (string.IsNullOrEmpty(request.ServerVariables["HTTP_X_FORWARDED_FOR"]))
ipString = request.ServerVariables["REMOTE_ADDR"];
else
ipString = request.ServerVariables["HTTP_X_FORWARDED_FOR"].Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).FirstOrDefault();
IPAddress result;
if (!IPAddress.TryParse(ipString, out result))
result = IPAddress.None;
return result;
}
public void logHit()
{
IPAddress ip = GetIp(Request);
string sIP = ip.ToString();
}
I tried this as well which yields the same result:
HttpContext.Current.Request.UserHostAddress;
When I do a call on the client side using something like the service on appspot, it works just fine:
<script type="application/javascript">
function getip(json) {
//txtIP is a input box on the form
document.getElementById("txtIP").value = json.ip;
}
</script>
<script type="application/javascript" src="http://jsonip.appspot.com/?callback=getip"></script>
I suppose I could do a round-about way by hitting that appspot link and parse it out but that seems like a whole lot of trouble for something that should be simple.
Could it be the IIS on the server? Some kind of redirect going on? The ip addresses logged are NOT the servers. The problem is I dont have direct access to it so I have to talk to the guys that admin it and would like to give them some direction before they just start changing things.
Thanks
Ernie
If the HTTP_X_FORWARDED_FOR header is truly supported, then I think this would not be either forward or reverse proxy server causing this, but more likely Dynamic Network Address Translation or Dynamic Port Address Translation, which is happening below the application layer on the TCP/IP stack and thus would not affect an HTTP request header.
There are many ways to configure NAT, most of which would not cause these symptoms, but it is certainly possible to configure NAT in a way that would present this problem. Dynamic NAT or Dynamic PAT would be two such examples, and I would suggest this is what you ask your network administrators.
For more on Dynamic NAT/PAT, with good examples, you could review: http://www.cisco.com/en/US/docs/security/asa/asa82/configuration/guide/nat_dynamic.html
In a typical NAT scenario, the request packets reach the NAT device (firewall or router) as:
FROM - 5.5.5.5 (public address of the client)
TO - 6.6.6.6 (the public address of the server)
The "typical" NAT configuration would rewrite only the destination, as follows:
FROM - 5.5.5.5
TO - 192.168.6.6 (the private address of the server)
In this typical case, the server would still see REMOTE_ADDR as 5.5.5.5, as that is the source address on the incoming request. Then, the packets would be returned to 5.5.5.5, and the response would return to the client successfully.
Now, in the case of dynamic PAT, for example, the request would reach the NAT device as follows:
FROM - 5.5.5.5
TO - 6.6.6.6
Then, the NAT device would rewrite both source and destination packets, maintaining this "dynamic" mapping for only the lifetime of the request:
FROM - 192.168.1.1:12345 (the dynamic PAT address)
TO - 192.168.6.6 (the private address of the server)
Now, when the server sees this request, it appears to be from private address 192.168.1.1. In fact, with a strict PAT all requests will appear to be from this address. In your case, there are 2 or 3 of these addresses, probably because you may have enough traffic that you risk running out of ports if you use only a single dynamic PAT address.
So, your REMOTE_ADDR is 192.168.1.1, because that is actually the source address on the request packets. There is no HTTP_X_FORWARDED_FOR, because the Dynamic PAT is occurring at a lower TCP/IP layer (address and not application).
Finally, the response is sent back to 192.168.1.1:12345, which routs to the NAT device, which for the duration of the request/response (see the Cisco documentation above) maps it back to 5.5.5.5, and then drops the "dynamic" mapping.
Everything worked perfectly, the client gets the response back, except that you have no idea of the actual client address from the viewpoint of the server. And if it is dynamic NAT in play, I don't see how you could get this information from the server.
Fortunately, you did exactly the right thing to get the information in javascript on the client, so this likely solves your problem as well as it could be solved.
It depends on your network structure. Simply a firewall or load balancer can change the variables which you are checking.
if you are using a load balancer check this:
How to get visitor IP on load balancing machine using asp.net
if your sever is behind a firewall check this:
Find if request was forwarded from firewall to IIS
Related
I am currently using Httpclient and I can successfully gather my data with a specific network/internet-connection at the place that has the data.
However when I try to gather the data at home with another internet-connection I receive an "NameResolutionFailure" error.
My goal is to be able to reach the data from any type of connection but I am not sure what I am quite missing here. (I am also new in this area).
This is the code that I use when I talk to the db:
string dataurl = "my-url-here";
var http = new HttpClientHandler()
{
Credentials = new NetworkCredential("user", "password", "domain"),
};
var httpClient = new HttpClient(http);
try
{
var result = await httpClient.GetStringAsync(dataurl);
System.Diagnostics.Debug.WriteLine(result);
}
catch (HttpRequestException ex)
{
if (ex.GetBaseException() != null)
{
System.Diagnostics.Debug.WriteLine(ex.GetBaseException().Message); //this is where i recieve the NameResolutionFailure error
}
else
{
System.Diagnostics.Debug.WriteLine(ex.Message);
}
}
How come I can only reach the data when I am on a certain network and not with every network? Am I missing code or is there something else in play here?
Appreciate every help, tips, code-examples i can get!
The problem is likely to be in the string dataurl = "my-url-here"; and where that's accessible from. There are likely to be two obstacles:
Name resolution
Network Access
While your error message only mentions Name resolution, I'm guessing you'll need to do something about network access as well.
Name resolution (or DNS) is about translating a host name into an I.P. address.
When you're on a work network, there'll be a name resolution service that resolves local computer names to I.P. addresses on the network. Normally these local computer names are not visible to public DNS servers. If you connect your device to a different network (e.g. a mobile network), it uses the public DNS servers, which know nothing about the local domain named computers.
For example MyServer might resolve on your local network because it's part of your local domain, and the local network infrastructure will sort that out. MyServer.MyCompany.com is usually similar, as by default machines names aren't exposed externally.
For a mobile application, you're going to need a public domain name. Something like MyServer.MyDomain.com (or www.google.com is the same thing, essential). A public DNS server translates this name to an I.P. address.
This is probably where the problem you're experiencing is occurring. You're probably using a local host name, that the public DNS servers don't know about.
If you're working for an organisation they may already have a domain, or you may need to purchase a domain for your application.
In the meantime you could look at one of the dynamic DNS solutions that may allow you to progress for development purposes.
For my Xamarin app, I use the name of the local machine when I'm developing, and the mobile device is on the same network.
If I'm not on the same network, I have a VPN that I can use. This connects into the work network as if I'm on the same network. If I'm developing at home and both devices are on my home network, I use the I.P. address of my development box, because I haven't made local DNS work on my home wifi.
When we go to release we use a public URL, like api.MyApp.com - which public DNS points to our prod server.
Network Access might be a thing that you need to deal with too.
A major part of a Network Engineer's job is to keep the hackers out. When your mobile device is on the same network as the server (i.e. when it's working for you), this isn't a problem because because mostly networks are configured so that two devices on the same network can see each other. It sounds like this is the sort of network you have, if your app can see your server on one connection.
But if you're needing to connect to your server from a mobile network, you need a way to tell your network router to forward specific traffic from the internet to your server.
This gets complicated, but for development purposes, strategies I've seen work are:
A VPN - we have a VPN that I fire up on the mobile device, enter my work network credentials, and then I can access my development box as if I'm on the same network
Virtual server / port forwarding - if you're at home, you can probably configure your modem to forward a particular port to your development box. Every modem is different, so you'd have to search up instructions for your particular one.
Network Engineer - if you're in a corporate, and want traffic from outside to get to a server that you're managing (and don't have a VPN), you probably need to talk to your networks department. Good luck.
I am trying to get Network IP Address as http://checkip.dyndns.org/ returns.
but i am getting this result from follwoing code.
fe80::28d3:b8e8:caab:63b3%10
i want ip address in internet dot-integer format lilke 122.168.149.143
foreach (IPAddress ipa in Dns.GetHostAddresses(Dns.GetHostName()))
{
if (ipa.AddressFamily == AddressFamily.InterNetwork)
{
textBox2.Text = ipa.ToString();
break;
}
}
You are currently filtering by IPv6 addresses when you mean to be filtering by IPv4 addresses! This is why IPAddress.ToString() is returning the IP in colon-hexadecimal notation.
To filter by IPv4 addresses you will need to filter according to AddressFamily.InterNetwork instead:
if (ipa.AddressFamily == AddressFamily.InterNetwork)
{ }
It is my understanding that you would like to obtain your public address. The code you listed will return your private (local) address!
The Windows Operating system does not care about your public IP. The Operating System simply routes out to the defined gateway and doesn't worry about the details. The only way to resolve your public IP is to query some external system. You need external help.
The most reliable way to obtain your public address is to connect to an external web server that can resolve and output your public address in plain-text. You already listed a suitable service with your question. You can even take responsibility for the service by providing the service yourself. The PHP code to achieve this is very simple.
If your router supports UPnP (or SNMP) you could query your router, although, this might not work. This might suffice for YOUR machine but some routers do not support UPnP and security conscious users may very well have disabled UPnP due to security holes. See this SO question for a managed UpNp library.
I have read that you can use tracert to an established website (one you know will be online) and the first "hop" will be to your route. I have never tried this.
The dot-integer format can be used only for IP ver. 4 addresses.
In the code sample you even explicitly select only IP ver. 6 addresses.
Use AddressFamily.InterNetwork instead of AddressFamily.InterNetworkV6 to select IPv4 address, then ToString will format it in the way you expect.
I try to get my correct IP but I can't
I'm using this code:
{
IPHostEntry host;
string localIP = "?";
host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
localIP = ip.ToString();
}
}
return localIP;
}
But it does not work for me!
For example my real IP is 151.246.147.86 but with this code I get 192.168.1.2.
Note: I have 4 Network adapters and in DOC with IPConfig I see this:
Network adapter: Local Area Connection 6
Media state : Media disconnected
Network adapter: Local Area Connection 4
Media state : Media disconnected
Network adapter: Local Area Connection 3
IP Address: 10.10.255.222
Network adapter: Local Area Connection
IP Address: 192.168.1.2
Now I connect to net and using with "Local Area Connection"; the public IP of my WAN connection is 151.246.147.86. I want to get this public IP (151.246.147.86), how can I do that?
Note : I don't want (and I can't, since I am using a VPN) use third party websites to get my IP
Please help!
-------EDIT :-------------
Note : I using from VPN and my VPN IP (for example) is : 176.227.197.111. But the IP of my WAN is: 151.246.147.86 and i want to get this address.
You (probably) are using a router/modem, therefore 192.168.1.2 is your "real IP". Your modem/router will be on the same (private) network, and its public interface (WAN) will have a public IP. So you need to get the IP on the public interface of your modem/router.
How to get the WAN IP of your modem depends on your mark and model; if it supports UPnP you can probably do it, or maybe if it is an enterprise class router it may also support SNMP...
You should specify your make and model.
Another way without using external sites: do a tracert to a known site (google?) the first hop will be your route.
Also, if you are on a VPN, you may be able to use the same technique. For example, if you know another host on the VPN (A server maybe?) you can ping/tracert it and discover your router from there. I don't know if in this case you will obtain what you call "a real IP" (by the way, how do you know this IP in the first place? You may be able to obtain it in the same way, programmatically).
Another solution for your VPN-based scenario: you can use Windows to help you. Windows has some kind of VPN management (RAS) which may help you; I would suggest starting from here to understand the basics, and then look for a library/SDK to help you (a quick google returned http://dotras.codeplex.com/).
What you ask is not possible unless there is some way to query your router/modem/external-most endpoint for its WAN address. The only IP address your computer knows about is its own (internal IP).
Technical note: there is nothing non-"real" about the IP address 192.168.1.2 - this is your computer's address. It is simply local to your given internal network and all but useless to anything outside.
If your router supports uPnP, you will need to query GetExternalIPAddress (starting point Is there a UPnP Library for .NET (C# or VB.NET)?). However since uPnP is considered dangerous and many security-conscious users turn it off, I would not count on it being enabled.
Querying an external service will be your most reliable bet for getting your external IP, whether it is one you write, or a third party service (see also https://superuser.com/questions/420969/services-that-just-return-your-public-ip-as-text).
There are many methods and tutorials that teach you how to find an ip address,I use this tool http://www.ipgp.net/ to display information about any ip address, just enter any IP address into the box and you will get the country, city, region, ISP, street address and the satellite location map for every query.
you're trying to get your IP address from your computer or a server? It will make a lot of difference. If you're trying to get your IP address from your computer/laptop use http://www.howtochangeipaddress.com. Your IP will pop up in front of you soon you enter the site.
Good afternoon,
Can anyone give any examples of how to obtain the IP Address of the local machine when it's connected to a remote windows domain network via VPN (RAS)? i.e. I need the VPN address and not the remote users local network address.
For example, my Server Side Windows Service communicates with my client side application and needs to create a log of all connected users and their IP Addresses.
This solution is easy enough when using a computer on the local network, but I wondered how I can go about getting the IP addresses of the users who are connected to the server via VPN. Please note that the IP address get method will be executed client side and sent to the server.
Here's my current code that works only when locally connected to the domain network:
public static string GetLocalIPv4()
{
string ipv4Address = String.Empty;
foreach (IPAddress currrentIPAddress in Dns.GetHostAddresses(Dns.GetHostName()))
{
if (currrentIPAddress.AddressFamily.ToString() == System.Net.Sockets.AddressFamily.InterNetwork.ToString())
{
ipv4Address = currrentIPAddress.ToString();
break;
}
}
return ipv4Address;
}
Our internal network is controlled by Windows SBS and uses a domain such as mycompany.local.
Thank you very much for your time and I look forward to reading your responses.
Rob
As the comment from #MarcB notes, cannot think of a good reason why you might want that info... so would be interesting if you could explain a use for this in an application just out of curiosity.
However, there are a lot of incorrect answers on here and online regarding enumerating IP addresses for a machine by using Dns.GetHostAddresses. It appears most people are not realizing the difference between looking up a machine name in the configured DNS resolver versus enumerating the machine address. These are very different things and while it might seem to return the right results in many cases, this is absolutely the wrong way to go about it because they are not the same thing. For example, see this link to an article on here where the original poster flagged an incorrect response as the answer but the correct response is below by #StephanCleary. See:
Get IPv4 Addresses
The difference is you want to look at the machines configuration and enumerate whatever IP address you are interested in locating from the machines own TCPIP stack. The code above and many of the incorrect responses try to lookup the name in the DNS resolver. Once you have that part correct, then you should be able to determine the VPN connection based on the network adaptor (by name or other attribute).
Im getting frustrated because of OpenDNS and other services (ie: roadrunner) that now always returns a ping even if you type any invalid url ie: lkjsdaflkjdsjf.com --- I had created software for my own use that would ping a url to verify if the site was up or not. This no longer works. Does anyone have any ideas about this?
Requirements:
It should work with any valid web site, even ones i dont control
It should be able to run from any network that has internet access
I would greatly appreciate to hear how others now handle this. I would like to add, im attempting to do this using System.Net in c#
Thank you greatly :-)
New addition: Looking for a solution that i can either buy and run on my windows machine, or program in c#. :-)
Update:
Thank you all very much for your answers. Ultimately i ended up creating a solution by doing this:
Creating a simple webclient that downloaed the specified page from the url (may change to just headers or use this to notify of page changes)
Read in xml file that simply lists the full url to the site/pages to check
Created a windows service to host the solution so it would recover server restarts.
On error an email and text message is sent to defined list of recipients
Most values (interval, smtp, to, from, etc) are defined in the .config for easy change
I will be taking some of your advice to add 'features' to this later, which includes:
AJAX page for real-time monitoring. I will use WCF to connect to the existing windows service from the asp.net page
Download Headers only (with option for page change comparison)
make more configurable (ie: retries on failure before notification)
Wget is a nice alternative. It will check not only whether the machine is active, but also whether the HTTP server is accepting connections.
You could create a simple web page with an address bar for the website and some javascript that uses AJAX to hit a site. If you get any HTTP response other than 200 on the async callback, the site isn't working.
<html>
<head>
<script language="javascript" type="text/javascript">
<!--
var ajax = new XMLHttpRequest();
function pingSite() {
ajax.onreadystatechange = stateChanged;
ajax.open('GET', document.getElementById('siteToCheck').value, true);
ajax.send(null);
}
function stateChanged() {
if (ajax.readyState == 4) {
if (ajax.status == 200) {
document.getElementById('statusLabel').innerHTML = "Success!";
}
else {
document.getElementById('statusLabel').innerHTML = "Failure!";
}
}
}
-->
</script>
</head>
<body>
Site To Check:<br />
<input type="text" id="siteToCheck" /><input type="button" onclick="javascript:pingSite()" />
<p>
<span id="statusLabel"></span>
</p>
</body>
This code depends on the browser not being IE and I haven't tested it, but it should give you a really good idea.
To see if a service is up, not only should you ping, but it's good to have scripts that will hit a service, such as a website, and get back a valid response. I've used What's Up Gold in the past, rather than write my own. I like all the features in products like that. such as sending me a page when a service is down.
For the record, lkjsdaflkjdsjf.com is a hostname (which at the moment is not registered to anyone). ping does not work with URLs, ping works with hostnames. hostnames are looked up using the Domain Name System. DNS is supposed to fail when hostnames are not registered.
The problem is that some services (apparently your ISP, and definitely OpenDNS) do NOT fail DNS requests for hostnames that aren't registered. Instead they return the IP address of a host on their network that presents a search page to any http request.
You appear to want to know two things: Is the name real (that is, is there a host with this name registered to some actual machine)? and Is that machine functioning?
If you already know that the name in question is real (for instance, you want to know if www.google.com is up), then you can use ping because you know that the name will resolve to a real address (the ISP can't return their IP for a registered name) and you'll only be measuring whether that machine is in operation.
If you don't know whether the name is real, then the problem is harder because your ISP is returning false data to your DNS request. The ONLY solution here is to find a DNS server that is not going to lie to you about unresolved names.
The only way I can think of to differentiate between your ISP's fake records and real ones is to do a reverse lookup on the IP you get back and see if that IP is in your ISP's network. The problem with this trick is that if the ISP doesn't have reverse DNS info for that IP, you won't know whether it's the ISP or just some knucklehead who didn't configure his DNS properly (I've made that mistake many times in the past).
I'm sure there are other techniques, but the fact that DNS lies underneath everything makes it hard to deal with this problem.
Don't directly know of any off the shelf options in c#, although I'd be very suprised if there aren't a few available.
I wrote something similar a few years ago, don't have the code anymore cos it belongs to someone else, but the basic idea was using a WebClient to hit the domain default page, and check for a http status code of 200.
You can then wire any notification logic around the success or fail of this operation.
If bandwidth is a concern you can trim it back to just use a HEAD request.
For more complex sites that you control, you can wire up a health monitoring page that does some more in depth testing before it sends the response, eg is DB connection up etc.
Often a machine that is dead on port 80 will still respond to a ping, so testing port 80 (or whatever other one you are interested in) will be a much more reliable way to go.
I've found ping to be very unreliable just because of all the hops you're having to jump through, and something in between can always interfere.
Trying to open up an http connection with a web server is probably the best way to go.
You could try running 'httping' if you have cygwin available or
http://freshmeat.net/projects/httping/
As far as I can see, the problem here that OpenDNS resolves invalid domains back to themselves to forward you on to something close to what you're after (so if you typo ggooggllee.com you end up at the right place via a bounce from the OpenDNS servers). (correct me if I'm wrong)
If that's the case, you should just be able to check whether the IP you've resolved == any of the IPs of OpenDNS? No more ping - no protocol (HTTP) level stuff - just checking for the exceptional case?
If you tend toward the sys-admin solution rather than the programming solution you could install a local name server and tell it not to accept anything but NS records for delegation only zones. This was the fix I (and I assumed everyone else on the internet) used when Network Solution/Verisign broke this last time. I installed BIND on a couple of local machine, told my DHCP servers to hand out those addrs as the local name servers, and set up something like the following for each of the delegation only zones that I cared about:
zone "com" { type delegation-only; };
zone "net" { type delegation-only; };
Come to think of this, I think this might be turned on by default in later BIND versions. As an added bonus you tend to get more stable DNS resolution than most ISPs provide, you control your own cache, a little patching and you don't have to rely on your ISP to fix the latest DNS attack, etc.
i like CALM for this sort of thing as it logs to a database and provides email notifications as well as a status dashboard
you can set up a test page on the site and periodically do a GET on it to receive either a 'true' result (all is well) or an error message result that gets emailed to you
caveat: i am the author of CALM