UDP receiver in Win32 Console

Source: Internet
Author: User

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 ()

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.