C# - 找到另一个程序实例以在同一网络上通过 TCP 进行通信的最快方法

C# - Fastest way to find another program instance to communicate via TCP on same network

我知道并非所有设备都会响应 ICMP 或 ping,因此最合适的方法似乎是向 LAN 上所有可能的 IP(从 192.168.0.0 到 192.168.255.255)发送 ARP 请求,但是意味着请求超过 65000 个 IP,这需要大量时间。我想找到我的程序的另一个实例以同步它们的内容,但我对 ARP 方法不满意。到目前为止,我已经在 SO 中找到了这些不错的代码:

[DllImport("iphlpapi.dll", ExactSpelling = true)]
public static extern int SendARP(int DestIP, int SrcIP, byte[] pMacAddr, ref uint PhyAddrLen);

static void Main(string[] args)
{
    List<IPAddress> ipAddressList = new List<IPAddress>();

    for (int i = 0; i <= 255; i++)
    {
        for (int s = 0; s <= 255; s++)
        {
            ipAddressList.Add(IPAddress.Parse("192.168." + i + "." + s));
        }
    }

    foreach (IPAddress ip in ipAddressList)
    {
        Thread thread = new Thread(() => SendArpRequest(ip));
        thread.Start();

    }
}

static void SendArpRequest(IPAddress dst)
{
    byte[] macAddr = new byte[6];
    uint macAddrLen = (uint)macAddr.Length;
    int uintAddress = BitConverter.ToInt32(dst.GetAddressBytes(), 0);

    if (SendARP(uintAddress, 0, macAddr, ref macAddrLen) == 0)
    {
        Console.WriteLine("{0} responded to ping", dst.ToString());
    }
}

但是如您所见,ARP 请求所有该范围将花费很长时间。在我的笔记本电脑上需要 10 到 15 分钟。当然,在大多数情况下,您会更快地找到所需的 IP,我的意思是这并不是说您的 PC 会落在 192.168.255.255 左右,但仍然需要几分钟。这只会完成一次,因为大多数时候 PC 和笔记本电脑使用首选 IP,除非更改,否则会保留数天或数月,因此只要它继续在该 IP 上工作,就不需要另一个 ARP 提取.到目前为止,最好的选择是让这个 "Hot start" 第一次发生并用加载屏幕装饰它,但我想知道是否有更快的方法来实现这一点。另外,我只在寻找 Windows 台电脑,因为它只是在同一应用程序的实例之间。

ICMP 和 ARP 用于定位设备,而不是服务。这就是 UDP 广播的设计目的。

使用 UdpClient on some port that you select. To find instances of your program on the subnet, send a packet to the broadcast 地址向您的程序添加 UDP 侦听器。子网上的所有机器都会收到数据包,任何 运行 您的程序都会 return 向发起者发送一个数据包,其中包含您需要了解的有关它们的任何信息。它可以是简单的 query/acknowledge 类型交换或丰富的信息集。

这样做的美妙之处在于,您发送一个数据包,得到一些响应,整个过程在几毫秒内就结束了……而且它在 /16 网络上的速度与在 /16 网络上的速度相同24... 或 /8 就此而言。

查看 this post 了解如何进行 UDP 广播的简单代码示例。