UDP client server echo example

Source: Internet
Author: User
Tags htons

Here's an example udp echo server I created from a simple UDP example (originally to help another thread question, now solved ). additionally, it shows how to use select () to poll the socket (with an optional time out ).

Compiled and tested on and between Win32/cygwin and Linux (wocould need to be modified for Win32/Winsock ).

Compile:
Gcc-wall-O client udpclient. c
Gcc-wall-O Server udpserver. c

Run:
./Server &
./Client 127.0.0.1 this is a test.

(Or run server in another console, separate machines, etc .).

Client:

/* Fpont 12/99 */
/* Pont.net */
/* Udpclient. C */

/* Converted to echo Client/Server with select () (timeout option )*/
/* 3/30/05 John Schultz */

# Include <stdlib. h>/* For exit ()*/
# Include <sys/types. h>
# Include <sys/socket. h>
# Include <netinet/in. h>
# Include <ARPA/inet. h>
# Include <netdb. h>
# Include <stdio. h>
# Include <unistd. h>
# Include <string. h>/* memset ()*/
# Include <sys/time. h>/* select ()*/

# Define remote_server_port 1500
# Define max_msg 100

/* Begin JCs 3/30/05 */

# Define socket_error-1

Int isreadable (int sd, int * error, int timeout) {// milliseconds
Fd_set socketreadset;
Fd_zero (& socketreadset );
Fd_set (SD, & socketreadset );
Struct timeval TV;
If (timeout ){
TV. TV _sec = timeout/1000;
TV. TV _usec = (timeout % 1000) * 1000;
} Else {
TV. TV _sec = 0;
TV. TV _usec = 0;
} // If
If (select (SD + 1, & socketreadset, 0, & TV) = socket_error ){
* Error = 1;
Return 0;
} // If
* Error = 0;
Return fd_isset (SD, & socketreadset )! = 0;
}/* Isreadable */

/* End JCs 3/30/05 */

Int main (INT argc, char * argv []) {

Int SD, RC, I, n, echolen, flags, error, timeout;
Struct sockaddr_in cliaddr, remoteservaddr, echoservaddr;
Struct hostent * h;
Char MSG [max_msg];

/* Check command line ARGs */
If (argc <3 ){
Printf ("Usage: % S <Server> <data1>... <datan>/N", argv [0]);
Exit (1 );
}

/* Get Server IP address (no check if input is IP address or DNS name */
H = gethostbyname (argv [1]);
If (H = NULL ){
Printf ("% s: Unknown host '% s'/N", argv [0], argv [1]);
Exit (1 );
}

Printf ("% s: sending data to '% s' (IP: % s)/n", argv [0], H-> h_name,
Inet_ntoa (* (struct in_addr *) H-> h_addr_list [0]);

Remoteservaddr. sin_family = H-> h_addrtype;
Memcpy (char *) & remoteservaddr. sin_addr.s_addr,
H-> h_addr_list [0], H-> h_length );
Remoteservaddr. sin_port = htons (remote_server_port );

/* Socket creation */
SD = socket (af_inet, sock_dgram, 0 );
If (SD <0 ){
Printf ("% s: cannot open socket/N", argv [0]);
Exit (1 );
}

/* Bind any port */
Cliaddr. sin_family = af_inet;
Cliaddr. sin_addr.s_addr = htonl (inaddr_any );
Cliaddr. sin_port = htons (0 );

Rc = BIND (SD, (struct sockaddr *) & cliaddr, sizeof (cliaddr ));
If (RC <0 ){
Printf ("% s: cannot bind port/N", argv [0]);
Exit (1 );
}

/* Begin JCs 3/30/05 */

Flags = 0;

Timeout = 100; // MS

/* End JCs 3/30/05 */

/* Send data */
For (I = 2; I <argc; I ++ ){
Rc = sendto (SD, argv [I], strlen (argv [I]) + 1, flags,
(Struct sockaddr *) & remoteservaddr,
Sizeof (remoteservaddr ));

If (RC <0 ){
Printf ("% s: cannot send data % d/N", argv [0], I-1 );
Close (SD );
Exit (1 );
}

/* Begin JCs 3/30/05 */

/* Init buffer */
Memset (MSG, 0x0, max_msg );

While (! Isreadable (SD, & error, timeout) printf (".");
Printf ("/N ");

/* Receive echoed message */
Echolen = sizeof (echoservaddr );
N = recvfrom (SD, MSG, max_msg, flags,
(Struct sockaddr *) & echoservaddr, & echolen );

If (n <0 ){
Printf ("% s: cannot receive data/N", argv [0]);
Continue;
}

/* Print received message */
Printf ("% s: echo from % s: UDP % u: % s/n ",
Argv [0], inet_ntoa (echoservaddr. sin_addr ),
Ntohs (echoservaddr. sin_port), MSG );

/* End JCs 3/30/05 */

}

Return 1;

}

Server:

/* Fpont 12/99 */
/* Pont.net */
/* Udpserver. C */

/* Converted to echo Client/Server with select () (timeout option). See udpclient. C */
/* 3/30/05 John Schultz */

# Include <stdlib. h>
# Include <sys/types. h>
# Include <sys/socket. h>
# Include <netinet/in. h>
# Include <ARPA/inet. h>
# Include <netdb. h>
# Include <stdio. h>
# Include <unistd. h>/* close ()*/
# Include <string. h>/* memset ()*/

# Define local_server_port 1500
# Define max_msg 100

Int main (INT argc, char * argv []) {

Int SD, RC, N, clilen, flags;
Struct sockaddr_in cliaddr, servaddr;
Char MSG [max_msg];

/* Socket creation */
SD = socket (af_inet, sock_dgram, 0 );
If (SD <0 ){
Printf ("% s: cannot open socket/N", argv [0]);
Exit (1 );
}

/* Bind local server port */
Servaddr. sin_family = af_inet;
Servaddr. sin_addr.s_addr = htonl (inaddr_any );
Servaddr. sin_port = htons (local_server_port );
Rc = BIND (SD, (struct sockaddr *) & servaddr, sizeof (servaddr ));
If (RC <0 ){
Printf ("% s: cannot bind Port Number % d/N ",
Argv [0], local_server_port );
Exit (1 );
}

Printf ("% s: Waiting for data on port UDP % u/N ",
Argv [0], local_server_port );

/* Begin JCs 3/30/05 */

Flags = 0;

/* End JCs 3/30/05 */

/* Server infinite loop */
While (1 ){

/* Init buffer */
Memset (MSG, 0x0, max_msg );

/* Receive message */
Clilen = sizeof (cliaddr );
N = recvfrom (SD, MSG, max_msg, flags,
(Struct sockaddr *) & cliaddr, & clilen );

If (n <0 ){
Printf ("% s: cannot receive data/N", argv [0]);
Continue;
}

/* Print received message */
Printf ("% s: From % s: UDP % u: % s/n ",
Argv [0], inet_ntoa (cliaddr. sin_addr ),
Ntohs (cliaddr. sin_port), MSG );

/* Begin JCs 3/30/05 */

Sleep (1 );
Sendto (SD, MSG, N, flags, (struct sockaddr *) & cliaddr, clilen );

/* End JCs 3/30/05 */

}/* End of server infinite loop */

Return 0;

}

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.