int recevfrom(int sock, void *buf, int len, // Receive buffer int flags, struct sockaddr *from, int *from_len); // Sender's network addr. |
|
Graphically:
|
Therefore:
|
Error: returns -1 Otherwise: returns the number bytes stored in buf |
Example:
/* ======================================== Assume we have done these already: create socket s bound s to a port ======================================== */ char line[1000]; /* User buffer to receive data */ struct sockaddr_in src_addr; /* Used to store sender's address */ int length; /* Length of the sockaddr_in data type */ /* --------------------------------------------------- Set up the length to tell recvfrom how much space it can write into the "src_addr" variable --------------------------------------------------- */ length = sizeof(src_addr); /* Length of the src_addr variable */ /* ---------------------------------------------------------- Receive the next message into the variable "msg" The sender of the message will be recorded in "src_addr" (You can use "src_addr" to reply to the sender !) ---------------------------------------------------------- */ recvfrom( s, line, 1000, 0 /* flags */, (struct sockaddr *)&src_addr, &length); |
How to run the program:
|
/* ---------------------------------------------------------- Receive the next message into the variable "msg" The sender of the message will be recorded in "src_addr" (You can use "src_addr" to reply to the sender !) ---------------------------------------------------------- */recvfrom( s, line, 1000, 0 /* flags */, (struct sockaddr *)&src_addr, &length); .... /* -------------------------------------------------- Program can send reply to sender using "src_addr" -------------------------------------------------- */ sendto( s , buf, length_of_buf, flags, (struct sockaddr *)&src_addr, &length); |