Can you bind() and connect() both ends of a UDP connection

gct picture gct · Mar 16, 2012 · Viewed 47k times · Source

I'm writing a point-to-point message queue system, and it has to be able to operate over UDP. I could arbitrarily pick one side or the other to be the "server" but it doesn't seem quite right since both ends are sending and receiving the same type of data from the other.

Is it possible to bind() and connect() both ends so that they send/receive only from each other? That seems like a nicely symmetric way to do it.

Answer

ximaera picture ximaera · Jul 12, 2018

Hello from the distant future which is the year 2018, to the year 2012.

There's, in fact, a reason behind connect()ing an UDP socket in practice (though blessed POSIX and its implementations don't in theory require you to).

An ordinary UDP socket doesn't know anything about its future destinations, so it performs a route lookup each time sendmsg() is called.

However, if connect() is called beforehand with a particular remote receiver's IP and port, the operating system kernel will be able to write down the reference to the route and assign it to the socket, making it significantly faster to send a message if subsequent sendmsg() calls do not specify a receiver (otherwise the previous setting would be ignored), choosing the default one instead.

Look at the lines 1070 through 1171:

if (connected)
    rt = (struct rtable *)sk_dst_check(sk, 0);

if (!rt) {
    [..skip..]

    rt = ip_route_output_flow(net, fl4, sk);

    [..skip..]
}

Until Linux kernel 4.18, this feature had been mostly limited to the IPv4 address family only. However, since 4.18-rc4 (and hopefully Linux kernel release 4.18 as well), it's fully functional with IPv6 sockets as well.

It may be a source of a serious performance benefit, though it will heavily depend on the OS you're using. At least, if you're using Linux and don't use the socket for multiple remote handlers, you should give it a try.