top | item 33287869

(no title)

dijonman2 | 3 years ago

I think connect() is for TCP, at least it is in C. As UDP is stateless you have to call send() for each packet.

discuss

order

ergl|3 years ago

You can actually use connect(2) for UDP. From the manual https://man7.org/linux/man-pages/man2/connect.2.html:

> 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.

After that, you can use send() instead of sendmsg(), so it saves you on having to pass the host on each call to sendmsg.

It can also avoid extra DNS lookups: everything is handled for you by the kernel. See also: https://stackoverflow.com/a/51296247

wjholden|3 years ago

Same in Java. For both TCP and UDP, you build a socket and write to that.

Actually, I don't know what happens if the DNS record expires during the connection. I would presume nothing -- that the socket will stay open with the same (possibly now invalid) destination IP until closed.