Write the UDP client/server program under Linux __linux

Source: Internet
Author: User
Tags stdin htons

First, the introduction
UDP is a kind of transport layer protocol in TCP/IP protocol, this paper introduces the method of programming Client/server model based on UDP protocol under Linux, and gives an echo client/server example program.

Brief introduction of UDP protocol
UDP is a simple Transport layer protocol, which is described in detail in RFC768. UDP protocol is a kind of connectionless and unreliable data message protocol, which is completely different from the TCP protocol which provides connection-oriented and reliable byte stream. Although UDP has a lot of deficiencies, there are still a lot of network programs that use it, such as DNS (Domain resolution Service), NFS (Network File system), SNMP (Simple Network Management Protocol) and so on.
Typically, a UDP client program does not establish a connection with the server program, but instead uses sendto () to send data directly. Similarly, the UDP server program does not need to allow the client program to connect, but instead uses recvfrom () directly to wait until the data sent by the client program is received.
Here, we use a simple echo Client/server program to introduce the way to write a UDP program under Linux. Client programs from stdin read data and sent over the network to the server program, the server program after receiving data directly back to the client program, the client program received the data returned by the server and then output from the stdout.

Third, UDP server program
1. Procedures for writing a UDP server program
(1) Use socket () to establish a UDP socket, the second parameter is Sock_dgram.
(2) Initialize the variable of the SOCKADDR_IN structure and assign the value. SOCKADDR_IN structure Definition:
struct SOCKADDR_IN {
uint8_t Sin_len;
sa_family_t sin_family;
in_port_t Sin_port;
struct IN_ADDR sin_addr;
Char Sin_zero[8];
};
This uses "08" as the port of the service program, using "Inaddr_any" as the binding IP address, which is the address on any host.
(3) Use BIND () to bind the socket above and the defined IP address and port. This checks to see if bind () is successful and exits if there are errors. This prevents problems that the service program will run repeatedly.
(4) Enter the infinite loop program, use Recvfrom () into the waiting state, until receiving the data sent by the client program, processing the received data, and send feedback to the client program. This is the direct sending of the received data back to the client program.

2, UDPSERV.C program content:
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>

#define Maxline 80
#define SERV_PORT 8888

void Do_echo (int sockfd, struct sockaddr *pcliaddr, socklen_t Clilen)
{
int n;
Socklen_t Len;
Char Mesg[maxline];

for (;;)
{
len = Clilen;
/* Waiting for receive data * *
n = recvfrom (SOCKFD, MESG, Maxline, 0, pcliaddr, &len);
/* Sent data back to client * *
SendTo (SOCKFD, MESG, N, 0, pcliaddr, Len);
}
}

int main (void)
{
int sockfd;
struct sockaddr_in servaddr, cliaddr;

SOCKFD = socket (af_inet, SOCK_DGRAM, 0); /* Create a socket * *

/* Init SERVADDR * *
Bzero (&servaddr, sizeof (SERVADDR));
servaddr.sin_family = af_inet;
SERVADDR.SIN_ADDR.S_ADDR = htonl (Inaddr_any);
Servaddr.sin_port = htons (Serv_port);

/* Bind address and port to socket * *
if (Bind (SOCKFD, (struct sockaddr *) &servaddr, sizeof (servaddr)) = = 1)
{
Perror ("bind error");
Exit (1);
}

Do_echo (SOCKFD, struct sockaddr *) &cliaddr, sizeof (CLIADDR));

return 0;
}


IV. UDP client program
1, the process of writing a UDP client program
(1) Initialize the variable of the SOCKADDR_IN structure and assign the value. This uses "8888" as the port of the connected service program, reads the IP address from the command-line arguments, and determines whether the IP address meets the requirements.
(2) Use socket () to establish a UDP socket, the second parameter is Sock_dgram.
(3) Use Connect () to establish a connection with the service program. Unlike the TCP protocol, the Connect () of UDP does not shake hands with the service program three times. Above we said that UDP is not connected, and can actually be connected. Udp,kernel using a connection can return an error message directly to the user program, thus avoiding the call to Recvfrom () because no data has been received. It looks as if the client program didn't respond.
(4) Send data to the service program because the UDP is connected, so write () is used instead of sendto (). The data here reads the user input directly from the standard input.
(5) The data returned by the receiving service program also uses read () to replace recvfrom ().
(6) Processing received data, here is the direct output to the standard output.

2, udpclient.c program content:
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <unistd.h>

#define Maxline 80
#define SERV_PORT 8888

void Do_cli (FILE *fp, int sockfd, struct sockaddr *pservaddr, socklen_t Servlen)
{
int n;
Char Sendline[maxline], recvline[maxline + 1];

/* Connect to Server * *
if (Connect (SOCKFD, (struct sockaddr *) pservaddr, servlen) = =-1)
{
Perror ("Connect error");
Exit (1);
}

while (Fgets (Sendline, Maxline, FP)!= NULL)
{
/* Read a line and send to server * *
Write (SOCKFD, Sendline, strlen (Sendline));
/* Receive data from server * *
n = Read (SOCKFD, recvline, maxline);
if (n = = 1)
{
Perror ("read error");
Exit (1);
}
Recvline[n] = 0; /* Terminate String * *
Fputs (Recvline, stdout);
}
}

int main (int argc, char **argv)
{
int sockfd;
struct sockaddr_in servaddr;

/* Check args * *
if (argc!= 2)
{
printf ("Usage:udpclient <ipaddress>/n");
Exit (1);
}

/* Init SERVADDR * *
Bzero (&servaddr, sizeof (SERVADDR));
servaddr.sin_family = af_inet;
Servaddr.sin_port = htons (Serv_port);
if (Inet_pton (Af_inet, argv[1], &servaddr.sin_addr) <= 0)
{
printf ("[%s] is not a valid ipaddress/n", argv[1]);
Exit (1);
}

SOCKFD = socket (af_inet, SOCK_DGRAM, 0);

DO_CLI (stdin, SOCKFD, (struct sockaddr *) &servaddr, sizeof (SERVADDR));

return 0;
}


V. Running the example program
1. Compile Example Program
Use the following command to compile the example program:
Gcc-wall-o Udpserv udpserv.c
Gcc-wall-o UdpClient udpclient.c
The compilation completed generates the Udpserv and udpclient two executable programs.

2, running the UDP server program
Execute the./udpserv & command to start the service program. We can use the NETSTAT-LN command to observe the IP address and port that the service program binds to, and some of the output information is as follows:
Active Internet connections (only servers)
Proto recv-q send-q Local address Foreign
TCP 0 0 0.0.0.0:32768 0.0.0.0:* LISTEN
TCP 0 0 0.0.0.0:111 0.0.0.0:* LISTEN
TCP 0 0 0.0.0.0:6000 0.0.0.0:* LISTEN
TCP 0 0 127.0.0.1:631 0.0.0.0:* LISTEN
UDP 0 0 0.0.0.0:32768 0.0.0.0:*
UDP 0 0 0.0.0.0:8888 0.0.0.0:*
UDP 0 0 0.0.0.0:111 0.0.0.0:*
UDP 0 0 0.0.0.0:882 0.0.0.0:*
You can see that the UDP has "0.0.0.0:8888" content, stating that the service program is working properly, you can receive any IP address on the host and port 8888 data.
If you then execute the./udpserv & Command, you will see the following information:
Bind error:address already in use
Indicates that a service program is already running.

3, running the UDP client program
Execute the./udpclient 127.0.0.1 command to start the client program and use the 127.0 0.1来 connection service to perform the following effects:
Hello, world!.
Hello, world!.
This is a test
This is a test
^d
The input data is returned correctly from the service program, press Ctrl+d to end the input and exit the program.
If the service program does not start, and the client program executes, you will see the following information:
$./udpclient 127.0.0.1
Test
Read Error:connection refused
Indicates that the specified IP address and port do not have a service program binding and the client program exits. This is the benefit of using connect (), and note that the error message is received after sending the data to the service program, not when the Connect () is invoked. If you use the Tcpdump program to grab the package, you will find that you receive an ICMP error message.

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.