Search code examples
c#network-programmingethernetswitching

c# - How to discovery all hosts connected to a Layer 2 Switch?


I have a Local Area Network like this: network configuration.

I'm writing a program in C#. This software runs on all hosts. The software needs to know which hosts are connected to its own Layer 2 Switch. It is very important that this is done without disturbing the server, because this software is for LanParty, and the hardware and the software on the server changes, as well as the same LAN.

It's not important to know the location of all hosts, but you just have to know which hosts are connected to the same switch.

In the example, "Host A" knows that "Host C" and "Host E" are connected to the same switch and all other hosts are not.


Solution

  • If the switches speak SNMP, you can simply ask them for their MAC address tables and figure out which hosts are connected where.

    If they don't, you'll have to resort to tricks like this:

    • Assume all hosts are connected to a single switch
    • Establish communication between all the hosts
    • assign roles to 3 arbitrary hosts: sender, receiver, sink
    • choose a MAC address not currently used in the network
    • receiver configures its NIC to the new MAC address and sends one packet to sink (all switches this packet passes through now know that address)
    • all other hosts set their NICs to promiscuous mode
    • sender sends a packet to receiver (if sender is connected to a switch that did not learn receiver's new address, that switch will flood out the packet on all ports. If one or more of those ports are connected to other switches that didn't learn the address either, these switches will also flood)

    So if any host other than receiver saw the second packet, this proves that host and sender are each connected to a switch which is not on the direct route between receiver and sink.

    Let's assume that sink, receiver and all listeners who didn't see the second packet are connected to one switch, sender and all listeners who did see it are connected to another one. Try again with a new MAC address and a new assignment of the three roles until you have sufficient information to figure out the network topology (or until you give up and accept the first assumption of a single switch).