views:

469

answers:

1

I have some networking code which connects to a multicast address but disconnects after a few seconds. Can anyone figure out what's wrong with this code?

String Target_IP = "224.1.2.3"; 
int Target_Port = 31337;

IPEndPoint LocalEP = new IPEndPoint(IPAddress.Any, Target_Port);
IPEndPoint RemoteEP = new IPEndPoint(IPAddress.Parse(Target_IP), Target_Port); 

using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
{
    s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true);
    //s.SetSocketOption(SocketOptionLevel.Udp, SocketOptionName.NoDelay, 1);
    //s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
    s.Bind(LocalEP);
    s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 0);
    s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(IPAddress.Parse(Target_IP)));
    s.Connect(RemoteEP);

    // TODO
}

After the Connect() function is called it reports as connected, but wait a second or two and it is disconnected. Am I binding to the wrong ports or something? Every online tutorial seems to do it a different way.

A: 

Since you are using UDP you cannot "connect" to the remote target. The Connect method on connectionless protocols does not connect as such but acts as a filter on what destintations it will accept packets from.

When you say you disconnect after a few seconds how are you determining that? If you are checking th connected status on the socket you are doing the wrong thing. Instead you should just start receiving and the only way to tell that the remote socket "may" have dropped off is if you get a 0 byte packet or you get an ICMP response from it.

sipwiz
If I try to send data without the connect function, I get an error which reads "A request to send or receive data was disallowed because the socket is not connected and no address was supplied". So how so I send data without connecting?
Nippysaurus
Do as the error says and specify the end point you want to send to http://msdn.microsoft.com/en-us/library/eae4f5y0.aspx. The key for you here is to understand the different approaches .Net uses for UDP and TCP. As you've found already Connect means different things for UDP and TCP.
sipwiz
That link you gave me is for UDP, but does not cover multicasting at all.
Nippysaurus