Detect the name of the network the server is connected to - c#

When developing an application at home or at work I need to comment the code that sets the proxy on or off. Because at home I am on a different network than at work, at home I don't need to use the proxy.
WebProxy proxy = new WebProxy(Settings.ProxyAddress, Settings.ProxyPort);
proxy.Credentials = CredentialCache.DefaultCredentials;
this.Proxy = proxy;
I would like to wrap this statement in a if-clause that determines the name of the network. Like
if(isCorporateNetwork) {.....set proxy...};
I tried to detect it with:
IPGlobalProperties.GetIPGlobalProperties().DomainName;
But that results as an empty string. Probably because my personal laptop is not a member of the domain. (However access to the network is granted by sending my credentials to the proxy, own devices are allowed to use the corporate network this way.)
How can I detect the name of the network that I am connected to?

Try to lookup your IP-address using DNS. (If you got a private IP you need to get the public through STUN or similar)
(This is just a different approach since yours seems to be the way to go: How to find FQDN of local machine in C#/.NET ?)

Related

Can't get public IP programatically, router settings issues?

In my program I am getting the local machine's public IP address like this
public static IPAddress getIPAddress()
{
IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());
foreach (IPAddress addr in localIPs)
{
if (addr.AddressFamily == AddressFamily.InterNetwork)
{
return addr;
}
}
return null;
}
and it worked fine where I live.
Right now I am at a friend's house, and I am connected to internet via Wi-Fi, and this code does not give me my external IP address, it has probably something to do with the router settings, but I am not very familiar with networks...
The router is TP-LINK, and I can access its settings like this
By the way, the 8080 port is exactly the one I need, I only need to be able to access my public IP. How can I do it?
You can make a request to a site like http://icanhazip.com/ to get your external IP address
var request = WebRequest.Create("http://ipv4.icanhazip.com/");
var response = request.GetResponse();
var dataStream = response.GetResponseStream();
var reader = new StreamReader (dataStream);
string myIPAddress = reader.ReadToEnd();
More info here: https://msdn.microsoft.com/en-us/library/456dfw4f%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396
There is no sure-fire way to do this that will work 100% of the time. However, there are two methods that will work most of the time.
The first is to use an external STUN server. It's relatively easy to add a configuration entry to your software to allow the user to change the STUN server if this server ever changes or goes down, they can choose another one.. there are many of them out there. A STUN server returns the users IP address back to the caller and is used by most VOIP devices.
The second is to use the built-in Universal Plug-n-Play framework (UPnP) to ask the router for its IP Address. This one, however, depends on the router supporting UPnP and it not being disabled. Additionally, UPnP may not work within a corporate network as there are several layers of routers and firewalls usually. Still, for home users this is typically a good option. There is a .NET based UPnP library here that utilizes the built-in COM based UPnP components in Windows:
http://managedupnp.codeplex.com/
I don't have any examples of how to implement this, but it supposedly has a good documentation library.
What you want is not possible. A router is a proxy of sorts, whereby all traffic must pass through it. The external IP address for all internal devices (including PCs, laptops, tablets, etc), will be the same--the internal IP address what is different. The only way for a device to know its external IP address is either to query the router (which might not be possible), or to query an external source. The port forwarding page you have in your post only shows the router where to redirect incoming traffic on that port, but it will tell the PC nothing as to what its external IP address is--because, generally, to the PC the external IP address is irrelevant.

Reverse IP Check Returning My Computer Name

I am trying to convert a VBScript COM component based Reverse/Forward IP checking system to C#.
This system was created to prevent the banning of SERPs like Googlebot using what was back then (becoming) the standard way of checking an IP was who it said it belonged to e.g a reverse/forward DNS check.
Although we have lists of SERP IP Ranges so we don't ban them if they come in - even with hack vectors - we cannot keep up with new ranges being added all the time.
The process is based around this short example.
It is explained simply here > http://ipadmin.junkemailfilter.com/rdns.php
This has been working fine for ages in VBScript but now I am converting to .NET I am having issues where people have set their IP to resolve to "localhost" like this one 113.168.154.182 as you just get back your own DNS server, Virgin media, or if I run it from my PC with c# I get my own computer name. The IP is from Vietnam > http://www.geoiptool.com/en/?ip=113.168.154.182
Now I am trying to use .NET and this code.
But as I am using this code to do get the hostname
IPHostEntry DNSHostIP = Dns.GetHostEntry("113.168.154.182");
hostname = DNSHostIP.HostName;
When I output the value of hostname I get my own computers name e.g std36w7.metal.mycompany.co.uk not localhost.
Then when I try and do a forward DNS check to get the list of IP addresses with this hostname I get my own IP addresses (one IPv6 one IPv4).
If I could get back "localhost" then I could have a check to skip it as a spoof along with anything starting with 10 or 192 etc.
However at the moment I cannot do this.
What is the best way of doing reverse/forward DNS checks which I thought was becoming the standard way of checking for spoofers nowadays in .NET?
And how can I handle people who have set (or some mistake might be causing it) their IP to be localhost.
Thanks
Simple. Your LOCAL DNS (guessing your router unless you have your own DNS server) is resolving it - upstream to it's INTERNET DNS server. Also if you really want it to return LOCALHOST, you'd have to literally edit your local HOSTS file and add an entry since no system ever returns the name LOCALHOST when you look up your ip even from a local DNS server. I believe the ONLY example is if you completely eliminate a DNS server to fallback on your local HOSTS file.

System.Web.HttpContext.Current.Request.UserHostAddress;

I am using the following code to obtain the user I.P. address but something strange is happening. I am, receiving the same ip address every time no matter if I am on my desktop or on my iPhone. I am on our network where the web servers live when I hit the page from my desktop but on my iPhone I was not even in the building. I have not run into this issue before, the ip address that I am getting back is an internal one assigned to the web servers.
string ip = System.Web.HttpContext.Current.Request.UserHostAddress;
Response.Write(ip);
Outside of my network I still get the same ip address 172.16.0.22 which is a router address, not our external ip. Is there a way to obtain the external ip address.
see this link http://thepcspy.com/read/getting_the_real_ip_of_your_users/
// Look for a proxy address first
_ip = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
// If there is no proxy, get the standard remote address
if (_ip == null || _ip.ToLower() == "unknown")
_ip = Request.ServerVariables["REMOTE_ADDR"];
I hope this will be resolved by this time, I ran into same issue. Like you we I knew the IP address was one of the server on the network (Load Balancer).
If your solution is load balanced web servers, then there are high chances that your load balancer is updating the request header information, rerouting through some software load balancer or something.
In case on local testing, update the router configuration to pass the request details. read some router configuration manual, there should be something which will have this setting. :)
Supply your router information, someone will have router/hardware knowledge on this.
I am not a hardware expert, but ask your network administrator to either pass-on the header info as is or at least update "X-Forwarded-For" information. So you can build code to read this information consistently.
Find more information about the traffic routing techniques used in industry and issues here.
Sanjay
Try this;
if (!String.IsNullOrEmpty(HttpContext.Current.Request.ServerVariables["HTTP_CLIENT_IP"]))
ipAddress = HttpContext.Current.Request.ServerVariables["HTTP_CLIENT_IP"];
else
ipAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
Request.UserHostAddress return server IP which IIS run on.

using httpListener to create custom website with URL as my IP-Address

I want to create a website with URL as my IP-address[ex: 192.X.X.X]
That website would respond with a "HELLO THERE" message to any user who accesses my URL.
I use the following code to do this![its just a basic code with no threading]
class listenToHTTP
{
HttpListener _listner;
public void start()
{
_listner = new HttpListener();
_listner.Prefixes.Add("http://localhost/");//default port 80
_listner.Start();
}
public void process()
{
while (true)
{
HttpListenerContext context = _listner.GetContext();
byte[] output = Encoding.ASCII.GetBytes("HELLO THERE");
context.Response.ContentEncoding = Encoding.ASCII;
context.Response.ContentLength64 = output.Length;
context.Response.OutputStream.Write(output, 0, output.Length);
}
}
}
The problem is that i dont know the IP-address through which anyone would access.
It perfectly shows the response "HELLO THERE" when I use http://localhost/ as URL.
But what IP-address would other people use so that they can access my simple website.
I have tried my IP-address in the browser but it doesnt work.
There are two things to look out for when doing this;
If you listen to a localhost address, only localhost will be able to connect to your HttpListener. You'll need to add a prefix with http://192.X.X.X/ (where the 192.X.X.X is your local IP of course) and listen to that. That may (depending on your operating system) require you to run as admin, at least if you want to do it on a port < 1024. You can test if this works by connecting to your IP# from your local machine instead of a localhost address.
If you're running Windows, the firewall may get in the way. If it seems to (ie you can connect to your IP# from the local machine but nothing else can connect) you'll need to open the port manually. There are plenty of guides how to do this on Google.
#Joachim reply is already good enough. I will like to add a bit more...
You need to expose the above mentioned IP address publicly to get the URL accessible to others.
In case of Exposing the URL to your domain only (i.e. in case of Intranet), check with your System Administrator to configure the IP Address on Intranet.
Localhost settings accessibility is confined to your machine only.
Make sure to check the firewall constraint for the URL accessibility to implement Point 1 or 2
For more information check the reference for HTTPListener
HTTPListener
HTTPListener
HTTPListener
The problem was that I was referring to a private network address which are local to the network and cannot be accessed by anyone outside that private network..
These are the range of ip-address that are used in private network and so systems with this address cannot be a server or host a website..
10.0.0.0 to 10.255.255.255
172.16.0.0 to 172.31.255.255
192.168.0.0 to 192.168.255.255
You should use a public address..

No response from sever on external IP in client-server IM app

I'm following a tutorial # http://www.geekpedia.com/tutorial239_Csharp-Chat-Part-1---Building-the-Chat-Client.html to try and gather the basics of networking. For those not wanting to hit the jump, it's a quick tut demonstrating how to program a simple client-server-model chat application.
When I try and run the code in the tut, it works fine as long as both the client and the server are on the same network, but the second I try and do it externally (getting a mate to run the client app, and running the server app my side), it all goes to pot. The fact that the code works when in the same network leads me to believe that it's not a coding issue, but an issue with the way my network is set up.
I'm trying to run the server on my IP address at port 21719, which I have opened, but still other people can't connect to my server, not able to get any form of response at all.
The code (from the tut) that is being used for the server to listen to connections is:
public void StartListening()
{
IPAddress ipaLocal = ipAddress; //ipAddress is parsed from txtIP
tlsClient = new TcpListener(ipaLocal, 21719);
tlsClient.Start();
ServRunning = true; //for the running loop
// Start the new tread that hosts the listener
thrListener = new Thread(KeepListening);
thrListener.Start();
}
Now, the tutorial does actually point out that
IPAddress ipaLocal = ipAddress;
Will cause issues on some configurations, and I'm beginning to fear that my configuration may be included in that.
So, does anyone have any solution for me?
Thanks,
Sam
What is the local IP address that you're using? (ipAddress) If it's 127.0.0.1, that's not correct (I don't know how it would work internally either, but Windows seems to use magic from time to time). Also, if you have multiple NICs in your local machine, maybe the port forwarding is only set up to forward to one of them, and you're using the IP of the other?
If that's not the problem, here are a few generic suggestions:
Grab a copy of netcat. It's a small network testing util whose only job is to form a simple TCP connection. That will allow you to eliminate your code as a variable in all this. If netcat can form a connection, then you know the problem is your code. If not, you've confirmed that it's your router.
You can use WireShark (or TShark) to look for ICMP packets. Capture ICMP packets on the remote machine. If you get "Destination Unreachable" from the router, you've again proved that it's your router.
As Spencer said you need to make sure Port Forwarding is setup on your router, to forward all packets that come in on port 21719 to your internal machine. As for exactly how to do that, it's hard to say without knowing what type of router.
Are you having people use your external (internet) IP address? (See yours here.)
Have you pinholed your router to forward all communications from port 21719 to your server?
Some tips:
What kind of operating system are you using? Please check the Scope and/or Profiles (under Advanced tab) of your firewall rule.
While your friend is trying to telnet to the port (connect to the im server) monitor the traffic using Wireshark or Network Monitor (Wireshark have problems with Vista and Win 7). If you don't see anything hitting your machine the problem is probably on the router side. Double check the settings - you said you set the forward rule (NAT) but did it also set the rule on firewall of your router?

Categories