SlideShare uma empresa Scribd logo
1 de 28
Chapter 8
Elementary UDP Socket
Contents
recvfrom and sendto Function
UDP Echo Server( main, de_echo Function)
UDP Echo Client( main, de_cli Function)
Lost datagrams
Verifying Received Response
Sever not Running
Connect Function with UDP
Lack of Flow Control with UDP
Determining Outgoing Interface with UDP
TCP and UDP Echo Server Using select
8.1 Introduction
   connectionless
   unreliable
   datagram protocol
   popular using
    DNS(the Domain Name System)
    NFS(the Network File System)
    SNMP(Simple Network Management Protocol)
UDP Server
                                          socket( )

                                            bind( )
UDP Client
 socket( )                                recvfrom( )

                                     block until datagram
 sendto( )                           received from a client
                  data(request)


                                         Process request

 recvfrom( )         data(reply)           sendto( )
  close( )
          Socket functions for UDP client-server
8.2 recvfrom and sendto Functions
 #include<sys/socket.h>

 ssize_t recvfrom(int sockfd, void *buff, size_t nbyte, int flag,
                  struct sockaddr *from, socklen_t *addrlen);

 ssize_t sendto(int sockfd, const void *buff, size_t nbyte, int flag,
                 const struct sockaddr *to, socklen_t addrlen);

         Both return: number of bytes read or written if OK,-1 on
 error
8.3 UDP Echo Server: main Function
              fgets             sendto                  recvfrom
      stdin           UDP                                            UDP
     stdout           client                                         server
              fputs              recvfrom                  sendto
                               Simple echo client-server using UDP

UDP echo server        #include “unp.h”
                       int main(int argc, char **argv)
                       {
                           int sockfd;
                           struck sockaddr_in servaddr,cliaddr;
                           sockfd=Socket(AF_INET,SOCK_DGRAM,0);
                           bzero(&servaddr,sizeof(servaddr));
                           servaddr.sin_fammily=AF_INET;
                           servaddr.sin_addr.s_addr=htonl(INADDR_ANY);
                           servaddr.sin_port=htons(SERV_PORT);
                           bind(sockfd, (SA *) &servaddr,sizeof(servaddr));
                           dg_echp(sockfd, (SA *) &cliaddr,sizeof(cliaddr));
                       }
8.4 UDP Echo Server:dg_echo Function
      #include “unp.h”
      void dg_echo(int sockfd, SA *pcliaddr, socklen_t clilen)
      {
         int n;
         socklen_t len;
         char mesg[MAXLINE];
         for( ; ; ) {
             len=clilen;
             n=Recvfrom(sockfd, mseg, MAXLINE, 0, pcliaddr, &len);
             sendto(sockfd, mesg, n, 0, pcliaddr, len);
           }
      }


               dg_echo funtion: echo lines on a datagram socket.
1.This function never
                           terminates.
                2.This function provides an iterative, not a concurrent
                    server as we had with
                              TCP

         connection    server    fock   listening   fock   server    connection
client                                                      child                 client
                        child            server




TCP                                      TCP                                      TCP

                 connection                                    connection



                      Summary of TCP client-server with two clients.
client                   server                     client


                                  Socket receive
                                     buffer



                          UDP                        UDP
UDP
           datagram                      datagram


         Summary of UDP client-server with two clients.
8.5 UDP Echo client: main Function
    #include “unp.h”
    int main(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);
    }
8.6 UDP Echo Client: dg_cli Function
    #include “unp.h”
    void dg_cli(FILE *fp, int sockfd, const SA *pservaddr, soklen_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);
        }
    }

                    dg_cli function: client processing loop
8.7 Lost Datagrams
If the client datagram arrives at the server
but the server’s reply is lost, the client will
again block forever in its call to recvfrom.

The only way to prevent this is to place a
timeout on the recvfrom.
8.8 Verify Received Response
#include “unp.h”
void dg_cli(FILE *fp, int sock, const SA *pseraddr, socklen_t servlen)
{
   int n;
   char sendline[MAXLINE], recvline[MAXLINE];
   socklen_t len;
   struct sockaddr *preply_addr;
   preply_addr = Malloc(servlen);

   while(Fget(sendline, MAXLINE, fp) ! = NULL) {
         Sendto(sockfd,sendline, strlen(sendline), 0, pservaddr, servlen);
         len = servlen;
         n = Recvfrom(sockfdm, recvline, MAXLINE, 0, preply_addr,&len)
continue
If(len != servlen || memcmp(pservaddr, preply_addr, len) != 0) {
                     printf(“reply from %s (ignore)n”,
                                Sock_ntop(preply_addr, len);
                     continue;
                }
                recvline[n] = 0;    /*NULL terminate */
                Fputs(recvline, stdout);
            }
        }
            Version of dg_cli that verifies returned socket address.


                    Bsdi.kohala.com has address 206.62.226.35
                    Bsdi.kohala.com has address 206.62.226.66


Solaris % udpcli02 206.62.226.66             The server has not bound an IP address
hello                                         to its socket, the kernel choose the source
reply from 206.62.226.35.7 (ignore)          address for the IP datagram. It is chosen
goodbye                                      to be the primary IP address of the outgoing
reply from 206.62.226.35.7 (ignore)          interface.
8.9 Server Not Running
 Client blocks forever in the call to recvfrom.

 ICMP error is asynchronous error.

  The basic rule is that asynchronous errors are not
returned for UDP sockets unless the socket has
been connected.
8.11 connect Function with UDP
This does not result in anything like a TCP
connection: there is no three-way handshake.
Instead, the kernel just records the IP address and
port number of the peer.

With a connect UDP socket three change:
1. We can no long specify the destination IP address
and port for an output operation. That is, we do not
use sendto but use write or send instead.

2. We do not use recvfrom but read or recv
instead.
3. Asynchronous errors are returned to the process for a
              connected UDP socket.



                          application                                peer




        ???
                            UDP         }   Stores peer IP address
                                            and port#from connect
                                                                     UDP

                                             UDP datagram
UDP datagram from
some other
IP address and/or port#                       UDP datagram
Datagrams arriving from any other IP address or port are not
     passed to the connected socket because either the source
     IP address or source UDP port does not match the protocol
     address to which the socket is connected.




                                          DNS
    DNS                  DNS                                  DNS
                                          clien
    client              server                                client
                                            t
  connect OK         cannot connect    cannot connect      cannot connect
(configured to use
   one server)
                                      (configured to use
                                         two server)
                                                               ?
8.12 dg_cli Function (Revisited)
 #include “unp.h”
 void dg_cli(FILE *fp, int sockfd, const SA *pservaddr, soklen_t servlen)
 {
     int n;
     char sendline[MAXLINE], recvline[MAXLINE+1];

     Connect(sockfd, (SA *) pservaddr, servlen);

     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);
     }
 }
8.13 Lack of Flow Control with UDP
  #include “unp.h”

  #define NDG 2000
  #define DGLEN 1400

  void dg_cli(FILE *fp, int sockfd, const SA *pservaddr, socklen_t, servlen)
  {
     int i;
     char sendline[MAXLINE];

      for(I = 0; I< NDG ; I++) {
          Sendto(sockfd, sendline, DGLEN, 0, pservaddr, servlen);
      }
  }
      dg_cli function that writes a fixed number of datagram to server
#include “unp.h”
static void recvfrom_int(int);
static int count;
void dg_echo(int sockfd, SA *pcliaddr, socklen_t clilen)
{
     socklen_t len;
     char mesg[MAXLINE];
     Signal(SIGHT, recvfrom_int);
     for( ; ; ) {
     len=clilen;
     Recvfrom(sockfd, mesg, MAXLINE, 0, pcliaddr, &len);
     count++;
     }
}

static void recvfrom_int(int signo)
{
      printf(“nreceived %d datagramn”, count);
      exit(0);
}
    dg_echo function that counts received datagram
The interface’s buffers were full or they could have been
discarded by the sending host.

  The counter “dropped due to full socket buffers” indicates how
many datagram were received by UDP but were discarded because
the receiving socket’s receive queue was full

  The number of datagrams received b the server in this example is
nondeterministic. It depends on many factors, such as the network
load, the processing load on the client host, and the processing load
in the server host.

  Solution
  fast server, slow client.
  Increase the size of socket receive buffer.
8.14 Determining Outgoing Interface with UDP
   This local address is chosen by searching the routing
   table for the destination IP address, and then using the
   primary IP address for the resulting interface.

     N= 240 * 1024;
     Setsockopt(sockfd, sol_SOCKET, so_RECVBUF, &n, sizeof(n));

              Increases the size of the socket receive queue
Connect(sockfd,(SA *) &servaddr, sizeof(servaddr));

        len = sizeof(cliaddr);
        Getsockname(sockfd, (SA *) &cliaddr, &len);
        printf(“local address &sn”,Soxk_ntop((SA *) &cliaddr, len);

        exit(0);

              Use connect to determine outgoing interface.



This local IP address is chosen by searching the routing table
for the destination IP address, and then using the primary IP
address for the resulting
8.15 TCP and UDP Echo Server Using select
    #include “unp.h”
    int main(int argc, char **argv)
    {
        int listenfd, connfd, udpfd, nready, maxfd1;
        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(&seraddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htol(INADDR_ANY);
servaddr.sin_port = htos(SERV_PORT);

Setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
Bind(listenfd, (SA *)&servaddr, sizeof(servaddr));

Listenfd, LISTENQ);
       /* Create UDP socket */
udpfd = Socket(AF_INET, SOCK_DGRAM, 0);

bzero(&seraddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htol(INADDR_ANY);
servaddr.sin_port = htos(SERV_PORT);

Bind(udpfd, (SA *) &servaddr, sizeof(servaddr));
Signal(SIGCHLD, sig_chld); /* must call waitpd( )*/
 FD_ZERO(&rset);
 maxfdp1=max(listenfd, udpfd)+1;
 for( ; ; ) {
      FD_SET(listenfd, &rset);
      FD_SET(udpfd, &rset);
      if((nready = selext[,axfdp1, &rset, NULL, NULL,NULL) < 0) {
           if(errno == EINTR)
                continue;
           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);
}
if(FD_ISSET(udpfd, &rset)) {
             len = sizeof(cliaddr);
             n = Recvfro,(udp, mesg, MAXLINE, 0, (SA *) &cliaddr, &len);

             Sendto(udpfd, ,esg, n, 0, (SA *) &cliaddr, len);
        }
    } /* for */
} /* main */

Mais conteúdo relacionado

Mais procurados

Mais procurados (20)

Socket programming
Socket programmingSocket programming
Socket programming
 
Socket Programming
Socket ProgrammingSocket Programming
Socket Programming
 
Protocols and the TCP/IP Protocol Suite
Protocols and the TCP/IP Protocol SuiteProtocols and the TCP/IP Protocol Suite
Protocols and the TCP/IP Protocol Suite
 
IPv4 Addressing
 IPv4 Addressing   IPv4 Addressing
IPv4 Addressing
 
Internet control message protocol
Internet control message protocolInternet control message protocol
Internet control message protocol
 
Ip addressing classful
Ip addressing classfulIp addressing classful
Ip addressing classful
 
IPv6 header
IPv6 headerIPv6 header
IPv6 header
 
Opnet lab 2 solutions
Opnet lab 2 solutionsOpnet lab 2 solutions
Opnet lab 2 solutions
 
Communication networks_ARP
Communication networks_ARPCommunication networks_ARP
Communication networks_ARP
 
S/MIME
S/MIMES/MIME
S/MIME
 
Network layer tanenbaum
Network layer tanenbaumNetwork layer tanenbaum
Network layer tanenbaum
 
Multicasting and multicast routing protocols
Multicasting and multicast routing protocolsMulticasting and multicast routing protocols
Multicasting and multicast routing protocols
 
Introduction to Data-Link Layer
Introduction to Data-Link LayerIntroduction to Data-Link Layer
Introduction to Data-Link Layer
 
Subnetting
SubnettingSubnetting
Subnetting
 
4. SMTP.ppt
4. SMTP.ppt4. SMTP.ppt
4. SMTP.ppt
 
Adoptive retransmission in TCP
Adoptive retransmission in TCPAdoptive retransmission in TCP
Adoptive retransmission in TCP
 
Mobile IP
Mobile IPMobile IP
Mobile IP
 
Unit 3 Network Layer PPT
Unit 3 Network Layer PPTUnit 3 Network Layer PPT
Unit 3 Network Layer PPT
 
TCP and UDP
TCP and UDP TCP and UDP
TCP and UDP
 
Computer network layers
Computer network layersComputer network layers
Computer network layers
 

Destaque

Udp socket programming(Florian)
Udp socket programming(Florian)Udp socket programming(Florian)
Udp socket programming(Florian)Flor Ian
 
Tuula Sjöstedt: Kestävän kaivostoiminnan verkosto
Tuula Sjöstedt: Kestävän kaivostoiminnan verkostoTuula Sjöstedt: Kestävän kaivostoiminnan verkosto
Tuula Sjöstedt: Kestävän kaivostoiminnan verkostoSitra / Ekologinen kestävyys
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postvamsitricks
 
Fredrik Ek 31.10.2012: Maatilojen sähkön ja lämmön yhteistuotantoratkaisut bi...
Fredrik Ek 31.10.2012: Maatilojen sähkön ja lämmön yhteistuotantoratkaisut bi...Fredrik Ek 31.10.2012: Maatilojen sähkön ja lämmön yhteistuotantoratkaisut bi...
Fredrik Ek 31.10.2012: Maatilojen sähkön ja lämmön yhteistuotantoratkaisut bi...Sitra / Ekologinen kestävyys
 

Destaque (8)

Udp socket programming(Florian)
Udp socket programming(Florian)Udp socket programming(Florian)
Udp socket programming(Florian)
 
Tuula Sjöstedt: Kestävän kaivostoiminnan verkosto
Tuula Sjöstedt: Kestävän kaivostoiminnan verkostoTuula Sjöstedt: Kestävän kaivostoiminnan verkosto
Tuula Sjöstedt: Kestävän kaivostoiminnan verkosto
 
Unit 5
Unit 5Unit 5
Unit 5
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,post
 
Unit 4
Unit 4Unit 4
Unit 4
 
Np unit iv ii
Np unit iv iiNp unit iv ii
Np unit iv ii
 
Np unit1
Np unit1Np unit1
Np unit1
 
Fredrik Ek 31.10.2012: Maatilojen sähkön ja lämmön yhteistuotantoratkaisut bi...
Fredrik Ek 31.10.2012: Maatilojen sähkön ja lämmön yhteistuotantoratkaisut bi...Fredrik Ek 31.10.2012: Maatilojen sähkön ja lämmön yhteistuotantoratkaisut bi...
Fredrik Ek 31.10.2012: Maatilojen sähkön ja lämmön yhteistuotantoratkaisut bi...
 

Semelhante a Npc08

Semelhante a Npc08 (20)

Socket programming-tutorial-sk
Socket programming-tutorial-skSocket programming-tutorial-sk
Socket programming-tutorial-sk
 
CODE FOR echo_client.c A simple echo client using TCP #inc.pdf
CODE FOR echo_client.c A simple echo client using TCP  #inc.pdfCODE FOR echo_client.c A simple echo client using TCP  #inc.pdf
CODE FOR echo_client.c A simple echo client using TCP #inc.pdf
 
Socket programming
Socket programmingSocket programming
Socket programming
 
Net Programming.ppt
Net Programming.pptNet Programming.ppt
Net Programming.ppt
 
Socket Programming Tutorial 1227317798640739 8
Socket Programming Tutorial 1227317798640739 8Socket Programming Tutorial 1227317798640739 8
Socket Programming Tutorial 1227317798640739 8
 
Socket Programming Tutorial
Socket Programming TutorialSocket Programming Tutorial
Socket Programming Tutorial
 
#1 (TCPvs. UDP)
#1 (TCPvs. UDP)#1 (TCPvs. UDP)
#1 (TCPvs. UDP)
 
Remote Procedure Call
Remote Procedure CallRemote Procedure Call
Remote Procedure Call
 
Network Prog.ppt
Network Prog.pptNetwork Prog.ppt
Network Prog.ppt
 
Basics of sockets
Basics of socketsBasics of sockets
Basics of sockets
 
gRPC in Go
gRPC in GogRPC in Go
gRPC in Go
 
EN-04 (1).pptx
EN-04 (1).pptxEN-04 (1).pptx
EN-04 (1).pptx
 
Pemrograman Jaringan
Pemrograman JaringanPemrograman Jaringan
Pemrograman Jaringan
 
Basic socket programming
Basic socket programmingBasic socket programming
Basic socket programming
 
lab04.pdf
lab04.pdflab04.pdf
lab04.pdf
 
Sockets intro
Sockets introSockets intro
Sockets intro
 
03 sockets
03 sockets03 sockets
03 sockets
 
Networking chapter III
Networking chapter IIINetworking chapter III
Networking chapter III
 
Sockets
Sockets Sockets
Sockets
 
Socket Programming
Socket ProgrammingSocket Programming
Socket Programming
 

Mais de vamsitricks (20)

Unit 6
Unit 6Unit 6
Unit 6
 
Np unit2
Np unit2Np unit2
Np unit2
 
Np unit iv i
Np unit iv iNp unit iv i
Np unit iv i
 
Unit 7
Unit 7Unit 7
Unit 7
 
Npc16
Npc16Npc16
Npc16
 
Npc14
Npc14Npc14
Npc14
 
Npc13
Npc13Npc13
Npc13
 
Unit 3
Unit 3Unit 3
Unit 3
 
Unit 2
Unit 2Unit 2
Unit 2
 
Unit 7
Unit 7Unit 7
Unit 7
 
Unit 6
Unit 6Unit 6
Unit 6
 
Unit4wt
Unit4wtUnit4wt
Unit4wt
 
Unit3wt
Unit3wtUnit3wt
Unit3wt
 
Unit2wt
Unit2wtUnit2wt
Unit2wt
 
Unit 1wt
Unit 1wtUnit 1wt
Unit 1wt
 
Jsp with mvc
Jsp with mvcJsp with mvc
Jsp with mvc
 
Cookies
CookiesCookies
Cookies
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,post
 
Javabeans
JavabeansJavabeans
Javabeans
 
Javabeanproperties
JavabeanpropertiesJavabeanproperties
Javabeanproperties
 

Npc08

  • 2. Contents recvfrom and sendto Function UDP Echo Server( main, de_echo Function) UDP Echo Client( main, de_cli Function) Lost datagrams Verifying Received Response Sever not Running Connect Function with UDP Lack of Flow Control with UDP Determining Outgoing Interface with UDP TCP and UDP Echo Server Using select
  • 3. 8.1 Introduction connectionless unreliable datagram protocol popular using DNS(the Domain Name System) NFS(the Network File System) SNMP(Simple Network Management Protocol)
  • 4. UDP Server socket( ) bind( ) UDP Client socket( ) recvfrom( ) block until datagram sendto( ) received from a client data(request) Process request recvfrom( ) data(reply) sendto( ) close( ) Socket functions for UDP client-server
  • 5. 8.2 recvfrom and sendto Functions #include<sys/socket.h> ssize_t recvfrom(int sockfd, void *buff, size_t nbyte, int flag, struct sockaddr *from, socklen_t *addrlen); ssize_t sendto(int sockfd, const void *buff, size_t nbyte, int flag, const struct sockaddr *to, socklen_t addrlen); Both return: number of bytes read or written if OK,-1 on error
  • 6. 8.3 UDP Echo Server: main Function fgets sendto recvfrom stdin UDP UDP stdout client server fputs recvfrom sendto Simple echo client-server using UDP UDP echo server #include “unp.h” int main(int argc, char **argv) { int sockfd; struck sockaddr_in servaddr,cliaddr; sockfd=Socket(AF_INET,SOCK_DGRAM,0); bzero(&servaddr,sizeof(servaddr)); servaddr.sin_fammily=AF_INET; servaddr.sin_addr.s_addr=htonl(INADDR_ANY); servaddr.sin_port=htons(SERV_PORT); bind(sockfd, (SA *) &servaddr,sizeof(servaddr)); dg_echp(sockfd, (SA *) &cliaddr,sizeof(cliaddr)); }
  • 7. 8.4 UDP Echo Server:dg_echo Function #include “unp.h” void dg_echo(int sockfd, SA *pcliaddr, socklen_t clilen) { int n; socklen_t len; char mesg[MAXLINE]; for( ; ; ) { len=clilen; n=Recvfrom(sockfd, mseg, MAXLINE, 0, pcliaddr, &len); sendto(sockfd, mesg, n, 0, pcliaddr, len); } } dg_echo funtion: echo lines on a datagram socket.
  • 8. 1.This function never terminates. 2.This function provides an iterative, not a concurrent server as we had with TCP connection server fock listening fock server connection client child client child server TCP TCP TCP connection connection Summary of TCP client-server with two clients.
  • 9. client server client Socket receive buffer UDP UDP UDP datagram datagram Summary of UDP client-server with two clients.
  • 10. 8.5 UDP Echo client: main Function #include “unp.h” int main(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); }
  • 11. 8.6 UDP Echo Client: dg_cli Function #include “unp.h” void dg_cli(FILE *fp, int sockfd, const SA *pservaddr, soklen_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); } } dg_cli function: client processing loop
  • 12. 8.7 Lost Datagrams If the client datagram arrives at the server but the server’s reply is lost, the client will again block forever in its call to recvfrom. The only way to prevent this is to place a timeout on the recvfrom.
  • 13. 8.8 Verify Received Response #include “unp.h” void dg_cli(FILE *fp, int sock, const SA *pseraddr, socklen_t servlen) { int n; char sendline[MAXLINE], recvline[MAXLINE]; socklen_t len; struct sockaddr *preply_addr; preply_addr = Malloc(servlen); while(Fget(sendline, MAXLINE, fp) ! = NULL) { Sendto(sockfd,sendline, strlen(sendline), 0, pservaddr, servlen); len = servlen; n = Recvfrom(sockfdm, recvline, MAXLINE, 0, preply_addr,&len) continue
  • 14. If(len != servlen || memcmp(pservaddr, preply_addr, len) != 0) { printf(“reply from %s (ignore)n”, Sock_ntop(preply_addr, len); continue; } recvline[n] = 0; /*NULL terminate */ Fputs(recvline, stdout); } } Version of dg_cli that verifies returned socket address. Bsdi.kohala.com has address 206.62.226.35 Bsdi.kohala.com has address 206.62.226.66 Solaris % udpcli02 206.62.226.66 The server has not bound an IP address hello to its socket, the kernel choose the source reply from 206.62.226.35.7 (ignore) address for the IP datagram. It is chosen goodbye to be the primary IP address of the outgoing reply from 206.62.226.35.7 (ignore) interface.
  • 15. 8.9 Server Not Running Client blocks forever in the call to recvfrom. ICMP error is asynchronous error. The basic rule is that asynchronous errors are not returned for UDP sockets unless the socket has been connected.
  • 16. 8.11 connect Function with UDP This does not result in anything like a TCP connection: there is no three-way handshake. Instead, the kernel just records the IP address and port number of the peer. With a connect UDP socket three change: 1. We can no long specify the destination IP address and port for an output operation. That is, we do not use sendto but use write or send instead. 2. We do not use recvfrom but read or recv instead.
  • 17. 3. Asynchronous errors are returned to the process for a connected UDP socket. application peer ??? UDP } Stores peer IP address and port#from connect UDP UDP datagram UDP datagram from some other IP address and/or port# UDP datagram
  • 18. Datagrams arriving from any other IP address or port are not passed to the connected socket because either the source IP address or source UDP port does not match the protocol address to which the socket is connected. DNS DNS DNS DNS clien client server client t connect OK cannot connect cannot connect cannot connect (configured to use one server) (configured to use two server) ?
  • 19. 8.12 dg_cli Function (Revisited) #include “unp.h” void dg_cli(FILE *fp, int sockfd, const SA *pservaddr, soklen_t servlen) { int n; char sendline[MAXLINE], recvline[MAXLINE+1]; Connect(sockfd, (SA *) pservaddr, servlen); 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); } }
  • 20. 8.13 Lack of Flow Control with UDP #include “unp.h” #define NDG 2000 #define DGLEN 1400 void dg_cli(FILE *fp, int sockfd, const SA *pservaddr, socklen_t, servlen) { int i; char sendline[MAXLINE]; for(I = 0; I< NDG ; I++) { Sendto(sockfd, sendline, DGLEN, 0, pservaddr, servlen); } } dg_cli function that writes a fixed number of datagram to server
  • 21. #include “unp.h” static void recvfrom_int(int); static int count; void dg_echo(int sockfd, SA *pcliaddr, socklen_t clilen) { socklen_t len; char mesg[MAXLINE]; Signal(SIGHT, recvfrom_int); for( ; ; ) { len=clilen; Recvfrom(sockfd, mesg, MAXLINE, 0, pcliaddr, &len); count++; } } static void recvfrom_int(int signo) { printf(“nreceived %d datagramn”, count); exit(0); } dg_echo function that counts received datagram
  • 22. The interface’s buffers were full or they could have been discarded by the sending host. The counter “dropped due to full socket buffers” indicates how many datagram were received by UDP but were discarded because the receiving socket’s receive queue was full The number of datagrams received b the server in this example is nondeterministic. It depends on many factors, such as the network load, the processing load on the client host, and the processing load in the server host. Solution fast server, slow client. Increase the size of socket receive buffer.
  • 23. 8.14 Determining Outgoing Interface with UDP This local address is chosen by searching the routing table for the destination IP address, and then using the primary IP address for the resulting interface. N= 240 * 1024; Setsockopt(sockfd, sol_SOCKET, so_RECVBUF, &n, sizeof(n)); Increases the size of the socket receive queue
  • 24. Connect(sockfd,(SA *) &servaddr, sizeof(servaddr)); len = sizeof(cliaddr); Getsockname(sockfd, (SA *) &cliaddr, &len); printf(“local address &sn”,Soxk_ntop((SA *) &cliaddr, len); exit(0); Use connect to determine outgoing interface. This local IP address is chosen by searching the routing table for the destination IP address, and then using the primary IP address for the resulting
  • 25. 8.15 TCP and UDP Echo Server Using select #include “unp.h” int main(int argc, char **argv) { int listenfd, connfd, udpfd, nready, maxfd1; 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);
  • 26. /* Create listening TCP socket */ listenfd = Socket(AF_INET,SOCK_STREAM, 0); bzero(&seraddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = htol(INADDR_ANY); servaddr.sin_port = htos(SERV_PORT); Setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)); Bind(listenfd, (SA *)&servaddr, sizeof(servaddr)); Listenfd, LISTENQ); /* Create UDP socket */ udpfd = Socket(AF_INET, SOCK_DGRAM, 0); bzero(&seraddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = htol(INADDR_ANY); servaddr.sin_port = htos(SERV_PORT); Bind(udpfd, (SA *) &servaddr, sizeof(servaddr));
  • 27. Signal(SIGCHLD, sig_chld); /* must call waitpd( )*/ FD_ZERO(&rset); maxfdp1=max(listenfd, udpfd)+1; for( ; ; ) { FD_SET(listenfd, &rset); FD_SET(udpfd, &rset); if((nready = selext[,axfdp1, &rset, NULL, NULL,NULL) < 0) { if(errno == EINTR) continue; 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); }
  • 28. if(FD_ISSET(udpfd, &rset)) { len = sizeof(cliaddr); n = Recvfro,(udp, mesg, MAXLINE, 0, (SA *) &cliaddr, &len); Sendto(udpfd, ,esg, n, 0, (SA *) &cliaddr, len); } } /* for */ } /* main */