This is the program that receives UDP data. to simplify the compilation of the program, some judgment errors are removed:
// Mywsksvr. cpp: defines the entry point of the console application.
# Include "stdafx. H"
# Include <Winsock. h>
# Include <stdio. h>
# Define recvlen 2000 // size of the receiving buffer
Char Buf [recvlen]; // receives the buffer
# Pragma comment (Lib, "ws2_32.lib ")
Int main ()
{
Wsadata wwsadata;
Word wWord;
WWord = makeword (1, 1 );
If (! Wsastartup (wWord, & wwsadata ))
{
// Create a socket
Socket sock;
If (sock = socket (af_inet, sock_dgram, 0/* ipproto_udp */))! = Invalid_socket)
{
// Bind the local address to the port
Sockaddr_in ADDR;
ADDR. sin_addr.s_addr = htonl (inaddr_any );
Addr. sin_family = AF_INET;
Addr. sin_port = htons (60000); // The port must be consistent with the sender to receive
// Bind
Bind (sock, (SOCKADDR *) & addr, sizeof (SOCKADDR ));
// Receive data
SOCKADDR_IN addrClient; // After receiving data from recvfrom, the address of the sending end is stored.
Int len = sizeof (SOCKADDR );
Int a, n;
Fd_set readfds;
Timeval timeout = {5, 0}; // The timeout value is 5 seconds, and the number next to it is the microsecond value.
While (1)
{
FD_ZERO (& readfds); // clear the contact between readfds and all handles.
FD_SET (sock, & readfds); // establishes the connection between readfds and sock.
N = select (0, & readfds, NULL, NULL, & timeout); // receives data
If (n> 0)
{
A = recvfrom (sock, buf, RECVLEN, 0, (SOCKADDR *) & addrClient, & len );
Printf ("recv % s, len = % d \ n", buf, );
If (a = SOCKET_ERROR) // Error
Printf ("*** ERROR. CODE = % d \ n", WSAGetLastError ());
}
Else
{
Printf ("% ds recv timeout \ n", timeout. TV _sec );
}
}
Closesocket (sock );
WSACleanup ();
}
}
} // Endof main ()