0

I'm writing a c# program where I should compare the current network the PC is connected to with a database.

With W-LAN its easy (SSID), but how can I identify the network if the user is connected via LAN and is the SSID the best solution?

Thanks.

Someone
  • 43
  • 8
  • What do you mean by identify the network? You want some unique identifier for the network? – Ron Beyer Dec 10 '15 at 18:14
  • Yes, something I can be "sure" that this the network that I am searching. – Someone Dec 10 '15 at 18:22
  • I think SSID is pretty unreliable. I mean how often have you connected to "Free Wifi"? What do you mean by local network? Same company, same local link, same what? I would tend towards grabbing the MAC address of the current default gateway, maybe? – Mirko Dec 10 '15 at 18:24
  • What is with networks that are very big with lots of subnets. Is does the MAC address method work here to or could there be another default gateway in another subnet? – Someone Dec 10 '15 at 18:35
  • There really isn't anything on a network that identifies it as unique. . An SSID is just a name given to a network, and is easily changed. You can try to get the MAC of the gateway/router, but yes there are no "rules" about having a single gateway (although your computer should only choose one). You could get a list of all the MAC's on the network and if its a certain % the same, assume its a particular network... The router MAC has an issue if the router is ever replaced, the MAC changes... – Ron Beyer Dec 10 '15 at 18:42

2 Answers2

0

Default Gateway will give you the IP address of the router you are connected to (or whatever is assigning you an IP address). Or you can get the MAC address of the gateway etc.

Matti Price
  • 3,351
  • 15
  • 28
  • Thanks a lot, I haven't thought about the MAC address. – Someone Dec 10 '15 at 18:19
  • @Someone, this won't necessarily work for some networks since they may be using multiple gateways or may use a First Hop Redundancy Protocol. You could get different gateway IP and MAC addresses on different hosts on the same network. The actual network address is about as close as I think you will be able to get to identify a particular network. – Ron Maupin Dec 10 '15 at 18:58
  • Yeah @RonMaupin is correct and there really isn't a "good" way to identify it unless you know more about the network structure etc. It's possible you could tracert to a known address and build a map that way, going to whatever level you want. But without at least some knowledge of the network, it's going to be mostly a guessing game. – Matti Price Dec 10 '15 at 19:04
  • @Someone, what is wrong with the actual network address? It is freely available to every host on the network. – Ron Maupin Dec 10 '15 at 19:07
  • But lets say it is not sooo important to get the right network and I just want to do something every time the SSID is "ExampleNetwork". Would at least something like that be possible in LAN? – Someone Dec 10 '15 at 19:14
  • @RonMaupin Hmm, I think this will do its job ;) – Someone Dec 10 '15 at 19:17
0

If you want to go the route of MAC for default gateway try this:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Threading.Tasks;

namespace NetworkIdentifier
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var macAddressOfGateway = GetMacAddressOfGateway();
            Console.WriteLine(macAddressOfGateway);
            Console.ReadLine();
        }

        private static string GetMacAddressOfGateway()
        {
            var networkInterface = GetBestNetworkInterface();
            var gatewayAddress = networkInterface.GetIPProperties().GatewayAddresses.FirstOrDefault();
            if (gatewayAddress == null)
            {
                throw new InvalidOperationException("No gateway!");
            }

            var mac = GetMacAddress(gatewayAddress.Address);

            return MacToString(mac);
        }

        private static string MacToString(byte[] mac)
        {
            return string.Format("{0:X2}:{1:X2}:{2:X2}:{3:X2}:{4:X2}:{5:X2}", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
        }

        public static NetworkInterface GetBestNetworkInterface()
        {
            var publicIpAddress = new IPAddress(0x08080808); // Googles DNS IP of 8.8.8.8 (Seems like a relatively safe hardcoded IP to pick :))
            var ipv4AddressAsUInt32 = BitConverter.ToUInt32(publicIpAddress.GetAddressBytes(), 0);
            uint interfaceindex;
            var result = Win32ApiCalls.GetBestInterface(ipv4AddressAsUInt32, out interfaceindex);
            if (result != 0)
            {
                throw new Win32Exception(result);
            }

            var networkCards = NetworkInterface.GetAllNetworkInterfaces().Where(x => x.OperationalStatus == OperationalStatus.Up);
            return networkCards.FirstOrDefault(networkInterface => networkInterface.GetIPProperties().GetIPv4Properties().Index == interfaceindex);
        }

        public static IPAddress GetDefaultGateway()
        {
            var networkInterface = GetBestNetworkInterface();
            if (networkInterface == null) return null;
            var address = networkInterface.GetIPProperties().GatewayAddresses.FirstOrDefault();
            return address.Address;
        }

        public static byte[] GetMacAddress(IPAddress address)
        {
            byte[] mac = new byte[6];
            uint len = (uint)mac.Length;
            byte[] addressBytes = address.GetAddressBytes();
            uint dest = ((uint)addressBytes[3] << 24)
              + ((uint)addressBytes[2] << 16)
              + ((uint)addressBytes[1] << 8)
              + ((uint)addressBytes[0]);
            if (Win32ApiCalls.SendARP(dest, 0, mac, ref len) != 0)
            {
                throw new Exception("The ARP request failed.");
            }
            return mac;
        }
    }

    public static class Win32ApiCalls
    {
        [DllImport("iphlpapi.dll", CharSet = CharSet.Auto)]
        public static extern int GetBestInterface(UInt32 destAddr, out UInt32 bestIfIndex);

        [DllImport("iphlpapi.dll", ExactSpelling = true)]
        public static extern int SendARP(uint destIP, uint srcIP, byte[] macAddress, ref uint macAddressLength);
    }
}

This needs a lot of clean up, caveating, error checking, etc. (and won't work on non-windows hosts, so don't even bother with dnxcore :))

** Caveat Emptor :)

Edit: Just removed my commented out lines as they didn't add anything useful

Mirko
  • 4,284
  • 1
  • 22
  • 19