Senden Sie eine UDP-multicast-Pakete auf alle meine IPs

Ich versuche zum senden einer multicast-Paket an alle meine Netzwerk-Schnittstellen(2 LAN, einer WLAN). Ich erstmal darauf folgte tutorial.

Das problem ich begegnen, ist, dass es scheint, dass das Paket zu sein scheint, mit nur einem meiner IP-Adresse.

Hier ist mein Derzeitiger code.

private static void SendOnAllCards(int port, String address)
{
    using (Socket mSendSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
    {
        mSendSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership,
                                    new MulticastOption(IPAddress.Parse(address)));
        mSendSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 255);
        mSendSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
        mSendSocket.Bind(new IPEndPoint(IPAddress.Any, port));
        IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(address), port);
        mSendSocket.Connect(ipep);


        byte[] bytes = Encoding.ASCII.GetBytes("This is my welcome message");
        mSendSocket.Send(bytes, bytes.Length, SocketFlags.None);
    }
}

Habe ich versucht, es manuell zu tun:

private static void SendOnAllCards(int port, string remoteAddressSrc)
{
    foreach (IPAddress remoteAddress in Dns.GetHostAddresses(Dns.GetHostName()).Where(i=>i.AddressFamily == AddressFamily.InterNetwork))
    {

        using (Socket mSendSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
        {
            mSendSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership,
                                        new MulticastOption(IPAddress.Parse(remoteAddressSrc)));
            mSendSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 255);
            mSendSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            mSendSocket.Bind(new IPEndPoint(IPAddress.Any, port));
            IPEndPoint ipep = new IPEndPoint(remoteAddress, port);
            mSendSocket.Connect(ipep);


            byte[] bytes = Encoding.ASCII.GetBytes("This is my welcome message");
            mSendSocket.Send(bytes, bytes.Length, SocketFlags.None);
        }
    }
}

Dies funktioniert, aber es impliziert, dass ich habe, um so viele sockel, die ich habe IP(in diesem Beispiel erstelle ich Ihnen auf jeden senden, aber es ist nur ein test), und ich mag nicht die Weise, die ich habe, um alle meine IPs.

Also, was ist der richtige Weg, dies zu tun?

Bearbeiten zweite bonus-Frage: Warum ist das arbeiten, wenn ich geben Sie die lokale ip in die Connect, die angeben, die remote-Adresse, aber nicht auf die Bind?

InformationsquelleAutor J4N | 2013-03-06
Schreibe einen Kommentar