Broadcasting UDP message to all the available network cards

后端 未结 4 1130
醉话见心
醉话见心 2020-12-05 08:37

I need to send a UDP message to specific IP and Port.

Since there are 3 network cards,

10.1.x.x
10.2.x.x
10.4.x.x

when i send a UD

4条回答
  •  孤城傲影
    2020-12-05 08:53

    Expansion of Rex's Answer. This allows you to not have to hard code the ip addresses that you want to broadcast on. Loops through all interfaces, checks if they are up, makes sure it has IPv4 information, and an IPv4 address is associated with it. Just change the "data" variable to whatever data you want to broadcast, and the "target" port to the one you want. Small drawback is that if an interface has multiple ip addresses associated with it, it will broadcast out of each address. Note: this will ALSO try to send broadcasts through any VPN adapter (via Network and Sharing Center/Network Connections, Win 7+ verified), and if you want to receive responses, you will have to save all the clients. You also will not need a secondary class.

        foreach( NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces() ) {
            if( ni.OperationalStatus == OperationalStatus.Up && ni.SupportsMulticast && ni.GetIPProperties().GetIPv4Properties() != null ) {
                int id = ni.GetIPProperties().GetIPv4Properties().Index;
                if( NetworkInterface.LoopbackInterfaceIndex != id ) {
                    foreach(UnicastIPAddressInformation uip in ni.GetIPProperties().UnicastAddresses ) {
                        if( uip.Address.AddressFamily == AddressFamily.InterNetwork ) {
                            IPEndPoint local = new IPEndPoint(uip.Address.Address, 0);
                            UdpClient udpc = new UdpClient(local);
                            udpc.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
                            udpc.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontRoute, 1);
                            byte[] data = new byte[10]{1,2,3,4,5,6,7,8,9,10};
                            IPEndPoint target = new IPEndPoint(IPAddress.Broadcast, 48888);
                            udpc.Send(data,data.Length, target);
                        }
                    }
                }
            }
        }
    

提交回复
热议问题