C# Is current network my domain - c#

I am building an add-on for office, in which I am to open a browser and navigate to an internal site, which is also exposed through dns, so that it can be accessed from outside the network/domain.
Now, in order to access this site, I need to know whether or not I am inside or outside the domain network. If I'm inside I need to access via internal ip otherwise through the exposed dns address.
This is where I ask the clever minds of stack overflow, if any of you know of a way to see if the network a computer is currently connected to, is indeed the network of the domain to which the computer/user belongs?
I have been looking at Environment.UserDomainName and Domain.GetComputerDomain. Both of these could help me find the domain name, in theory (not tested, but expect it to work), but none of them helps me to find whether or not the current network is the domain network.
Any constructive feedback is very much appreciated!
EDIT
At some point this add-on is supposed to be sold to various customers, so I can't rely on something as simple as the IP looking in a specific way.
The solution must be something that can work regardless of the network the computer is connected to.

If your network gives computers unique names you can check the computer name by
Dns.GetHostName();
Or if your network has a specifically unique IP header (All IPs start with 10.1 or they are all on a Belkin router whose IPs start with 198.2) you can get all IP addresses using
IPAddress[] addr = Dns.GetHostAddresses(Dns.GetHostName());
UPDATE:
Something that shows my company's network is its DNS Suffix. Would this work for you?
NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface adapter in adapters)
{
IPInterfaceProperties properties = adapter.GetIPProperties();
Console.WriteLine(adapter.Description);
Console.WriteLine(" DNS suffix................................. :{0}",
properties.DnsSuffix);
Console.WriteLine(" DNS enabled ............................. : {0}",
properties.IsDnsEnabled);
Console.WriteLine(" Dynamically configured DNS .............. : {0}",
properties.IsDynamicDnsEnabled);
}

Related

Get the IP address that is used to connect to Internet. Discard virtual networks

The question "How to get the IP address?" maybe seems topical and already answered in S.O., but I'm having troubles in the circunstances that I explain below.
I'm writting a simple helper class to provide miscellaneous networking utilities that will help me in my development. I would like to write a function that will return the Ipv4 or Ipv6 of the current machine, the same Ip that is used when I navigate through a web browser, you know... just the relevant Ip of the user, and I would like to do it without queryng to a random site to discover the Ip address that is used.
For most people the task would be simple as this:
(From ip As IPAddress In Dns.GetHostEntry(Dns.GetHostName).AddressList()
Where ip.AddressFamily = AddressFamily.InterNetwork).FirstOrDefault
Or by iterating the System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces interfaces to do the same, however, I found that methodology is not efficient in most scenarios...
In my system I have 4 adapters, from those 4 adapters 2 are virtual adapters created by VMWare WorkStation (which are threated as Ethernet adapters), one virtual adapter from TAP-Win32 driver, and the "real" or physical Ethernet adapter that I use to navigate through Internet.
So, in C# or VB.Net, how can I Identify the proper adapter to retrieve the real Ip that is used to connect to Internet? the same Ip that returns websites like this?.
Note that when I ask "how to identify the proper adapter" what I'm asking is "how to identify the preferred adapter that the system will use to connect to Internet?", because an user could have many physical Ethernet adapters but only one will be the "preferred" to connect to Internet, then... how to do this?.
Here is a solution in vb.net using LINQ:
Function GetIP() As String
Return (
From networkInterface In networkInterface.GetAllNetworkInterfaces()
Where networkInterface.NetworkInterfaceType = NetworkInterfaceType.Ethernet
From address In networkInterface.GetIPProperties().UnicastAddresses
Where address.Address.AddressFamily = Net.Sockets.AddressFamily.InterNetwork
Select ip = address.Address.ToString()
).FirstOrDefault()
End Function

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.

C#: Query DHCP for Client Name

Final edit for clarity - In my environment, DNS will only store one record per client. If a client has multiple NICs, or changes subnets, the original IP is registered in DNS until the corresponding DHCP record expires (this is an AD environment where DHCP registers DNS addresses).
In this scenario DNS has one, incorrect, record for the client. I want to query DHCP by client name, to see all IPs that are leased to it.
The only possible solution I have found is to dump all subnet info from DHCP (supported by the below API) then query against that, but that is not feasible in my environment, since multiple people would use this application, and I don't want the additional strain on DHCP.
I cannot change any configuration for DNS or DHCP.
Thanks,
This is similar to this question, but with the referenced API (here), I can only query via IP. Is it possible with this API, or any other, to query DHCP by hostname? (The issue being, DNS gives me an old IP for MachineA, I want to retrieve any other IPs being leased by MachineA from the DHCP server).
Edit: To clarify, I want to write a program that I can type in a hostname, it will then query a DHCP server for all IPs for that hostname in any subnet administered by that DHCP server. This is to workaround the issue of a machine with multiple NICs registering an IP that is useless to me (wireless), so for instance the DNS result may be NICA (wireless) but I want NICB (wired).
From what I can tell, you've encountered the age-old problem of which IP address to use. Now-a-days many computers have multiple NICs, some virtual, some local-only, some with internet access, etc... For the application to choose is very difficult. Most of the time I simply make the IP by which the application hosts things like sockets a configuration item--simply because the application is incapable of really choosing which is the right ip address to use. e.g. two NICs both with the same network access, which do you choose? If you run the application twice, maybe one should use NIC 1 and the other should use NIC 2--how would the app make that determination? (i.e. it can't).
Having said that, depending your needs, you can go looking for the best NIC and get it's IP address. For example, if you want an IPv4 address on a non-wireless NIC, you can do something like:
var ips = from ni
in NetworkInterface.GetAllNetworkInterfaces()
where ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet
from ip in ni.GetIPProperties().UnicastAddresses
where ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork && ip.IsDnsEligible
select ip;
IPAddress address = ips.First().Address;
...error checking omitted for readability--apply whatever error checking suitable for your requirements.
You can even go so far as to check whether the address is link local (i.e. can communicate out of the local network segment--which usually means an address automatically assigned by Windows instead of DNS/DHCP) by seeing if the first two bytes of an IPv4 address are 169 and 254.
But, you need to specifically define what your requirements are. simply to say "undesirable wireless IP" doesn't provide unambiguous and verifiable criteria to tell what solution will always work for your needs.
If you are trying to locate a machine on the network, then querying DNS is probably what you want to do first. i.e. Think of a machine that has a static ip address on the network. It would register its name with the name service only, it would not show up in DHCP att all if the machine's IP stack is configured with the static address only.
I'm not sure how long it should take for a new machine or a recently changed IP address to show up in DNS. But if you want to see if DHCP has something different(newer), then query DHCP after trying it from DNS first.

how to get mac address of client that browse web site by asp.net mvc c#

I'm trying to get mac address from the client's machine that browse my web site, I've been used this:
using System.Management;
class Sample_ManagementClass
{
public static int Main(string[] args)
{
ManagementClass objMC = new
ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection objMOC = objMC.GetInstances();
foreach (ManagementObject objMO in objMOC)
{
if (!(bool)objMO["ipEnabled"])
continue;
Console.WriteLine((string)objMO["MACAddress"]);
}
}
}
But it is not recognized Management Namespace, so what should I do?
it's unfortunately not possible to reliably get the mac address of the client machine due to firewalls, proxies and ISP generic addresses being given. However, you can make a stab at getting the ip address by using:
var remoteIpAddress = Request.UserHostAddress;
However, this may or may not actually represent the client machine and is more likely the ISP gateway or some other ip address. It's a well known problem and one that even google have found hard to crack using clientside javascript (the idea here being that you get the actual local ip address via a js library and pass that over to your server function).
[edit] - might be worth taking a look at the following for inspiration/confirmation of the issue:
http://www.dotnetfunda.com/forums/thread2088-how-to-get-mac-address-of-client-machine.aspx
It is usually not possible for a person to get the MAC address of a computer from its IP address alone. These two addresses originate from different sources. Simply stated, a computer's own hardware configuration determines its MAC address while the configuration of the network it is connected to determines its IP address.
However, computers connected to the same TCP/IP local network can determine each other's MAC addresses. The technology called ARP - Address Resolution Protocol included with TCP/IP makes it possible. Using ARP, each computer maintains a list of both IP and MAC addresses for each device it has recently communicated with.
Src

detect ip conflict using C#

Is there any way to detect the message IP conflict? I will be using this in a thread in my program.
If your problem is locating the alert window saying there is a duplicate IP on the network, I suggest your use the API to enumerate all windows and see if the alert window is there.
You may be helped by Visual Studio tool Spy++ to see the characteritics of the window.
The question is not particular precise and old but I'll give it a go anyways because I wondered what I can do about such problems since I'm writing an app that manipulates IP addresses on the PC in order to launch applications which are dependent on specific addresses.
If anyone else has the same question I suggest trying to avoid any conflicts in the first place.
The thing is that setting an IP address is an administrative task and should only be done "free-handed" by people who know what they are doing. If you are setting IP addresses via code is is your task as a developer to check if the address to set is valid and not already known on the network.
First: Query DNS if this address belongs to a host other than the one the app runs on
Second: If DNS doesn't know about the address, send Ping requests to the address.
See: Check Local Ip Address
public static bool IsLocalIpAddress(string host)
{
try
{
// get host IP addresses
IPAddress[] hostIPs = Dns.GetHostAddresses(host);
// get local IP addresses
IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());
// test if any host IP equals to any local IP or to localhost
foreach (IPAddress hostIP in hostIPs)
{
// is localhost
if (IPAddress.IsLoopback(hostIP)) return true;
// is local address
foreach (IPAddress localIP in localIPs)
{
if (hostIP.Equals(localIP)) return true;
}
}
}
catch { }
return false;
}
If you want to "listen" for conflicts, the WMI and EventLog is the way to go. The EventLog is pretty much the first place where such conflicts surface and it is easy to monitor.

Categories