UDP is a connectionless transmission protocol provided on the network.
UDP communication has the following features:
- 1. Data Transmission is unreliable because no connection is required;
- 2. Data Transmission is intended for the entire network. Any computer in the LAN can receive the same data;
The specific implementation is very simple, but I rarely see this code on the network. I also read the original code and some books about UDP Communication on VCKBASE and wrote this simple client, the acceptor program plays a leading role, hoping to give some reference to the comrades who are new to udp broadcast programming.
Let me talk about the workflow, the receiver program:
Start the SOCKET library. The version is 2.0 WSAStartup (0x0202, & wsdata );
Then assign two addresses, one for binding the socket and the other for receiving messages from the broadcast address on the network;
...... A. sin_family = AF_INET;. sin_addr.s_addr = 0;. sin_port = htons (5050); from. sin_family = AF_INET; from. sin_addr.s_addr = INADDR_BROADCAST; from. sin_port = htons (5050); int fromlength = sizeof (SOCKADDR); // use UDP to initialize socket s = socket (AF_INET, SOCK_DGRAM, 0 ); // set this socket to broadcast type, setsockopt (s, SOL_SOCKET, SO_BROADCAST, (char FAR *) & optval, sizeof (optval )); // bind the socket to a specific address (s, (sockaddr *) & a, sizeof (sockaddr_in); char buf [256]; while (1) {// receive messages from the broadcast address. Note that the address used for binding is different from the address used for receiving messages. recvfrom (s, buf, 256, 0, (struct sockaddr FAR *) & from, (int FAR *) & fromlength); Sleep (2000); printf ("% s", buf); ZeroMemory (buf, 256 );}.....
The connectionless protocol does not require LISTEN or ACCEPT. It directly receives messages from the broadcast address, but we must set this socket to the broadcast type.
The sending program is relatively simple. You only need to change the sending Address to the BROADCAST address and set the socket to the BROADCAST type. For details, see the source code.
In VC6. Run in 0 WIN 2000.