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

后端 未结 10 1546
悲&欢浪女
悲&欢浪女 2020-12-01 04:40

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 do

相关标签:
10条回答
  • 2020-12-01 04:51

    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.

    0 讨论(0)
  • 2020-12-01 05:03

    Really the key is connect():

    If the socket sockfd is of type SOCK_DGRAM then addr is the address to which datagrams are sent by default, and the only address from which datagrams are received.

    0 讨论(0)
  • 2020-12-01 05:04

    I have not used connect() under UDP. I feel connect() was designed for two totally different purposes under UDP vs TCP.

    The man page has some brief details on the usage of connect() under UDP:

    Generally, connection-based protocol (like TCP) sockets may connect() successfully only once; connectionless protocol (like UDP) sockets may use connect() multiple times to change their association.

    0 讨论(0)
  • 2020-12-01 05:07

    This page contains some great info about connected versus unconnected sockets: http://www.masterraghu.com/subjects/np/introduction/unix_network_programming_v1.3/ch08lev1sec11.html

    This quote answers your question:

    Normally, it is a UDP client that calls connect, but there are applications in which the UDP server communicates with a single client for a long duration (e.g., TFTP); in this case, both the client and server can call connect.

    0 讨论(0)
提交回复
热议问题