UNP summary Chapter 8 basic UDP socket programming

Source: Internet
Author: User

 

1. Overview

Some common applications written using UDP include DNS (Domain Name System), NFS (Network File System), and SNMP (Simple Network Management Protocol)

Provides typical function calls for UDP client/server programs:

 

 

 

2. recvfrom and sendto Functions

Two functions are similar to the standard read and write Functions, but three additional parameters are required.

# Include <sys/socket. h> explain recvfrom (int sockfd, void * buff, size_t nbytes, int flags, struct sockaddr * from, socklen_t * addrlen); ssize_t sendto (int sockfd, const void * buff, size_t nbytes, int flags, const struct sockaddr * to, socklen_t addrlen); // all return: the number of bytes read or write if the operation succeeds, with an error of-1

The first three parameters: sockfd, buff, and nbytes are equivalent to the first three parameters of read and write: Description, pointer to read/write buffer, and number of read/write bytes.

The parameter to of the sendto function is a set of interface address structures containing the Protocol addresses (such as IP addresses and port numbers) to which data will be sent. Its size is specified by addrlen. The recvfrom function uses the Protocol address of the datagram sender to load the from interface address structure. The number of bytes stored in the interface address structure is also returned to the caller by an integer referred to by addrlen. Note that the last parameter of sendto is an integer, while the last parameter value of recvfrom is a pointer to an integer (value-result parameter ).

The last two parameters of recvfrom are similar to the last two parameters of accept: when the interface address structure is returned, the content of the interface address structure tells us who sent the datagram (in UDP) or who initiated the connection (in the case of TCP ). The last two parameters of sendto are similar to the last two parameters of connect: We use datagram to send (UDP) or establish a connection with it (TCP) to fill in the interface address structure.

It is feasible to write a datagram with a length of 0, which also means that for the datagram protocol, recvfrom returns a value of 0, which does not indicate that the other party has closed the connection, this is different from the case where the read on the TCP interface returns 0. Because UDP is not connected, there is no such thing as closing the UDP connection.

PS: by default, the recvfrom function is blocked when it does not receive data from the other party.

 

 

 

3. UDP connect function

We can call connect for UDP interfaces, but the result is different from that of TCP connections: There is no three-way handshake process. The kernel only records the IP address and port number of the other party. They are contained in the address structure of the set interface passed to connect and are immediately returned to the calling process.

 

Compared with the default non-connection interfaces, UDP APIs have three changes:

1 ). we can no longer specify the IP address and port number for the output operation, that is, we do not use sendto, but use write or send instead, any content written to the connected UDP interface is automatically sent to the Protocol address (such as IP address and port number) specified by connect)

2 ). instead of using recvfrom to learn the sender of the datagram, we use read, recv, or recvmsg instead, the data packets returned by the kernel for the input operation on a connected UDP interface are only those from the Protocol address specified by connect. The destination is the local Protocol address of the connected UDP interface, but the source is not the datagram of the Protocol address previously connect to the interface, and will not be delivered to the interface. In this way, a connected UDP interface is restricted and only one peer can exchange data packets.

3). asynchronous errors caused by connected UDP sets of interfaces are returned to the process in which they are located, but UDP socket not connected does not accept any asynchronous errors.

 

 

Processes that have a connected udp socket call connect again for the following purposes

  • Specify the new IP address and port number
  • Disconnect sleeve Interface

The first purpose (that is, to specify a new peer for a connected UDP Interface) is different from the use of connect in the TCP socket port: For the TCP socket interface, connect can only be called once.

To disconnect a connected UDP interface, we set the address cluster member (sin_family) of the interface address structure to AF_UNSPEC when we call connect again. In this case, an EAFNOSUPPORT error may be returned, but it does not matter. To disconnect a set of interfaces, the connect process is called on the connected UDP set interface.

 

 

4. UDP echo service program

 

1). main Function

#include     "unp.h"intmain(int argc, char **argv){    int     sockfd;    struct sockaddr_in servaddr, cliaddr;    sockfd = Socket(AF_INET, SOCK_DGRAM, 0);    bzero(&servaddr, sizeof(servaddr));    servaddr.sin_family = AF_INET;    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);    servaddr.sin_port = htons(SERV_PORT);    Bind(sockfd, (SA *) &servaddr, sizeof(servaddr));    dg_echo(sockfd, (SA *) &cliaddr, sizeof(cliaddr));}

 

2). dg_echo Function

#include     "unp.h"voiddg_echo(int sockfd, SA *pcliaddr, socklen_t clilen){    int     n;    socklen_t len;    char    mesg[MAXLINE];    for ( ; ; ) {        len = clilen;        n = Recvfrom(sockfd, mesg, MAXLINE, 0, pcliaddr, &len);        Sendto(sockfd, mesg, n, 0, pcliaddr, len);    }}

 

5. UDP bounce client program

1). main Function

#include     "unp.h"intmain(int argc, char **argv){    int     sockfd;    struct sockaddr_in servaddr;    if(argc != 2)       err_quit("usage: udpcli <IPaddress>");    bzero(&servaddr, sizeof(servaddr));    servaddr.sin_family = AF_INET;    servaddr.sin_port = htons(SERV_PORT);    Inet_pton(AF_INET, argv[1], &servaddr.sin_addr);    sockfd = Socket(AF_INET, SOCK_DGRAM, 0);    dg_cli(stdin, sockfd, (SA *) &servaddr, sizeof(servaddr));    exit(0);}

 

2). dg_cli function (non-connect)

#include     "unp.h"voiddg_cli(FILE *fp, int sockfd, const SA *pservaddr, socklen_t servlen){    int     n;    char    sendline[MAXLINE], recvline[MAXLINE + 1];    while (Fgets(sendline, MAXLINE, fp) != NULL) {        Sendto(sockfd, sendline, strlen(sendline), 0, pservaddr, servlen);        n = Recvfrom(sockfd, recvline, MAXLINE, 0, NULL, NULL);        recvline[n] = 0;        /* null terminate */        Fputs(recvline, stdout);    }}

 

3). dg_cli function (connect)

#include     "unp.h"voiddg_cli(FILE *fp, int sockfd, const SA *pservaddr, socklen_t servlen){    int     n;    char    sendline[MAXLINE], recvline[MAXLINE + 1];    Connect(sockfd, (SA *) pservaddr, servlen);    while (Fgets(sendline, MAXLINE, fp) != NULL) {        Write(sockfd, sendline, strlen(sendline));        n = Read(sockfd, recvline, MAXLINE);        recvline[n] = 0;        /* null terminate */        Fputs(recvline, stdout);    }}

 

 

6. TCP and UDP echo server programs using the select function

#include     "unp.h"intmain(int argc, char **argv){    int     listenfd, connfd, udpfd, nready, maxfdp1;    char    mesg[MAXLINE];    pid_t   childpid;    fd_set  rset;    ssize_t n;    socklen_t len;    const int on = 1;    struct sockaddr_in cliaddr, servaddr;    void    sig_chld(int);        /* create listening TCP socket */    listenfd = Socket(AF_INET, SOCK_STREAM, 0);    bzero(&servaddr, sizeof(servaddr));    servaddr.sin_family = AF_INET;    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);    servaddr.sin_port = htons(SERV_PORT);    Setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));    Bind(listenfd, (SA *) &servaddr, sizeof(servaddr));    Listen(listenfd, LISTENQ);         /* create UDP socket */    udpfd = Socket(AF_INET, SOCK_DGRAM, 0);    bzero(&servaddr, sizeof(servaddr));    servaddr.sin_family = AF_INET;    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);    servaddr.sin_port = htons(SERV_PORT);    Bind(udpfd, (SA *) &servaddr, sizeof(servaddr));    Signal(SIGCHLD, sig_chld);     /* must call waitpid() */    FD_ZERO(&rset);    maxfdp1 = max(listenfd, udpfd) + 1;    for ( ; ; ) {        FD_SET(listenfd, &rset);        FD_SET(udpfd, &rset);        if ( (nready = select(maxfdp1, &rset, NULL, NULL, NULL)) < 0) {            if (errno == EINTR)                continue;     /* back to for() */            else                err_sys("select error");         }         if (FD_ISSET(listenfd, &rset)) {             len = sizeof(cliaddr);             connfd = Accept(listenfd, (SA *) &cliaddr, &len);             if ( (childpid = Fork()) == 0) { /* child process */                 Close(listenfd);     /* close listening socket */                 str_echo(connfd);    /* process the request */                 exit(0);              }              Close(connfd);     /* parent closes connected socket */         }          if (FD_ISSET(udpfd, &rset)) {             len = sizeof(cliaddr);             n = Recvfrom(udpfd, mesg, MAXLINE, 0, (SA *) &cliaddr, &len);              Sendto(udpfd, mesg, n, 0, (SA *) &cliaddr, len);         }    }}

 

 

 

 

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.