Reputation: 12064
Well, my question may look like a basic stuff, but i am new to network programming side. I wish to know:
1) Is it always required to bind a socket in order to receive message from that? I saw a sniffer code (raw socket) one in which directly it is invoking recvfrom
and another piece of code in which it is invoking bind
and then a receive.
2) What is the difference between the AF_* and PF_* family? Is the later related to POSIX? Which is the one recommended ?
Upvotes: 13
Views: 13697
Reputation: 11
For a client that only sends data, a bind is not necessary.
For a client that is sending a request to a server, and then receiving a response, a bind is not necessary. The server can use the IP address and port number that the incoming data came from.
For a client that is only receiving data, or is receiving data before it sends out data back to the server, a bind is necessary. How will the server know where to send data to? In this sense the "client" is acting like a "server" that needs a place (bound port) for the data to come to.
Upvotes: 1
Reputation: 595827
I don't know about Linux, but on Windows, if recvfrom()
is called on an unbound socket, it will fail with an WSAEINVAL
error.
Upvotes: 0
Reputation: 63538
No, you don't need to bind().
If you're using a TCP or UDP socket where you are planning to either connect() or send a packet to a destination with sendto(), the kernel will automatically bind the socket to a suitable port number when you try to connect or send. This is generally the preferred way. bind()ing client sockets is considered harmful.
The same is also true of AF_UNIX sockets - the client side does not need to bind, and should not do so normally.
Upvotes: 13