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

2019-01-08 15:19发布

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.

标签: c linux udp
9条回答
爷的心禁止访问
2楼-- · 2019-01-08 15:43

UDP is connectionless, so there's little sense for the OS in actually making some sort of connection.

In BSD sockets one can do a connect on a UDP socket, but this basically just sets the default destination address for send (instead giving explicitly to send_to).

Bind on a UDP socket tells the OS for which incoming address to actually accept packets (all packets to other addresses are dropped), regardless the kind of socket.

Upon receiving you must use recvfrom to identify which source the packet comes from. Note that if you want some sort of authentication, then using just the addresses involved is as insecure as no lock at all. TCP connections can be hijacked and naked UDP literally has IP spoofing written all over its head. You must add some sort of HMAC

查看更多
虎瘦雄心在
3楼-- · 2019-01-08 15:48

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.

查看更多
可以哭但决不认输i
4楼-- · 2019-01-08 15:48

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.

查看更多
登录 后发表回答