Previous: http://www.bkjia.com/kf/201112/115686.html
5.8. sendto () and recvfrom () --- Talk To Me, Datagram
"That's good," you said. "But you haven't talked about the connectionless datagram socket ?" No problem. Now let's start this content.
Since the datagram socket is not connected to the remote host, what information do we need before sending a packet? Yes, it's the target address!
Sendto () function prototype:
Int sendto (intsockfd, const void * msg, int len, unsigned int flags,
Const struct sockaddr * to, socklen_ttolen );
As you can see, except for the other two information, the rest are the same as the function send. To is a pointer to the data structure struct sockaddr. It contains the IP address and port information of the destination. Tolen can be easily set to sizeof (struct sockaddr ). Similar to the send () function, sendto () returns the actual number of bytes sent (it may be smaller than the number of bytes you want to send !), Or return-1 in case of an error.
Recvfrom () function prototype:
Int recvfrom (intsockfd, void * buf, int len, unsigned int flags,
Struct sockaddr * from, int * fromlen );
Again, this function is the same as recv () except for the two added parameters. From is a pointer to the local data structure struct sockaddr. Its content is the IP address and port information of the source machine. Fromlen is a local pointer of the int type, and its initial value is sizeof (struct sockaddr ). After the function is returned, fromlen stores the length of the address actually stored in from.
Recvfrom () returns the length of the received bytes, or-1 if an error occurs.
From the column xiaobin_HLJ80