C# – Is broadcasting faster than a random SYN/ACK scan for a particular port


The project I'm working on uses P2P to transfer data between peers much unlike Bittorrent. This component does a random scan on each interface to see what devices are on the network. So far it has been implemented as a Socket connection which checks whether it has succeeded in connecting by trying to connect to the program's listening port. I'm wondering if it would be faster to rip this out and do a broadcast on each interface. Would this be faster/more reliable?

The current code for connection is as follows:

Socket testSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
testSock.BeginConnect(iep, new AsyncCallback(ConnectedAsync), testSock);
for (int i = 0; i <= iterations && Thread.CurrentThread.IsAlive; i++)
     if (testSock.Connected)

The 'random' component is a simple

Random r = new Random();

for each interface's subnet.

From my experience with broadcasting (Wireshark, DHCP etc) I'm under the impression that broadcasting will be truckloads faster and use heaps less resources. The reason I ask is that the person who wrote it is a smart guy and I'm wondering why he didn't use broadcasting.

So is it worth the effort?

Best Solution

Broadcasting is liable to be filtered out by certain equipment. It will be unreliable past one network segment - if what you are doing is confined to a LAN (or single network segment), then broadcasting should indeed be singificantly faster.

That being said, random searching will never be efficient or optimal. You will likely miss nodes, have issues with the scan taking longer than expected, etc. Since you have access to the subnet mask, you should be able to calculate a list of potentially valid nodes on the segment easily enough, however again - if you are confined within a single network segment (or collection of them), then broadcasting is the way to go.

If you are searching for a list of valid WAN nodes (ie not just one segment), then you will potentially be sending a lot of unwanted traffic. My advice there would be simply to have each node capable of sending a cache of other nodes to each other, then require a single node's address as user-input to bootstrap onto the network.

Related Question