Search code examples
c#socketsudpsystem.net.sockets

Why does socket.BeginConnect() always succeed even if there is no server


Why does Socket.BeginConnect() always succeed? I've made the following code to illustrate my point, if you run just this code there is no server listening, nothing it can possibly connect to and yet it works without problem.

private static Socket mSocket;
static void Main(string[] args)
{
    mSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
    IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050);
    mSocket.BeginConnect(remoteEndPoint.Address, remoteEndPoint.Port, new AsyncCallback(OnConnect), null);
    Console.Read();
}

static void OnConnect(IAsyncResult asyncResult)
{
    try
    {
        mSocket.EndConnect(asyncResult);
        Console.WriteLine(mSocket.Connected);
    }
    catch(Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}

Some of the System.Net.Sockets.Socket methods do not work if you use: SocketType.Dgram, ProtocolType.Udp like Socket.Listen() but Socket.Connect/BeginConnect() still do, this is nice which means the client has the exact same code for UDP as TCP (which i already have) but why? UDP is supposed to be connection less so making a connection (for me) does not make sense.

If there was an Socket.accept which worked in accepting a UDP client that wanted to connect I might understand (because then it would stay uniform and you could use either one for TCP or UDP)


Solution

  • "Connecting" a UDP socket just means that the target address is set on the socket. But contrary to TCP no packets will be exchanged with the peer so it is not known if the server can be reached at all.