SlideShare ist ein Scribd-Unternehmen logo
1 von 38
Downloaden Sie, um offline zu lesen
Session NM056

Programming TCP/IP
    with Sockets

   Geoff Bryant
 Process software
Course Roadmap

     NM055 (11:00-12:00) Important Terms and
     Concepts
           TCP/IP and Client/Server Model
           Sockets and TLI
           Client/Server in TCP/IP
     NM056 (1:00-2:00) Socket Routines
     NM057 (2:00-3:00) Library Routines
     NM058 (3:00-4:00) Sample Client/Server
     NM059 (4:00-5:00) VMS specifics (QIOs)
     NM067 (6:00-7:00) Clinic - Q&A
Slide 57                              Portions Copyright © 1996, Opus1, Process Software, TGV
TCP/IP Programming

Slides and Source Code available via anonymous FTP:

     Host::     ftp.process.com
     Directory: [pub.decus]
     Slides:    DECUS_F96_PROG.PS
     Examples: DECUS_F96_PROG_EXAMPLES.TXT

     Host:     ftp.opus1.com
     Slides:   DECUS_F96_PROG.PS
     Examples: DECUS_F96_PROG_EXAMPLES.TXT



Slide 58                              Portions Copyright © 1996, Opus1, Process Software, TGV
Programming with Sockets
                          Roadmap
     Berkeley Socket History
     Overview of the Socket Paradigm
     Socket addresses
     Other programming models




Slide 59                       Portions Copyright © 1996, Opus1, Process Software, TGV
Berkeley Socket History

     Documented in such books as
           Stevens’s Unix Network Programming
           Comer’s Internetworking with TCP/IP, vol III
     First provided with Berkeley Software
     Distribution (BSD 4.1c) Unix for the VAX
     Popularized in the 1986 4.3BSD release




Slide 60                                Portions Copyright © 1996, Opus1, Process Software, TGV
Other Programming Models

     Socket model is widely used
           mainly due to wide implementation of BSD
           networking kernel
           Avaible for Unix, Windows, VMS, ...
     Other models may be used in different
     environments
           STREAMS model (UNIX System V)
           Others



Slide 61                               Portions Copyright © 1996, Opus1, Process Software, TGV
Socket Paradigm Overview

     A socket is a communications endpoint
     In BSD networking, it is a data structure
     within the kernel
     A socket is “named” by its socket address
     A connection is represented by two
     communicating sockets




Slide 62                         Portions Copyright © 1996, Opus1, Process Software, TGV
Using sockets is like using
                                the file system
 Server      socket()                                   Client
                                         socket()
               bind()

              listen()

             accept()
  block until             connection     connect()
  connection from        establishment
  client
               read()                     write()

               write()                    read()


              close()                     close()

Slide 63                                        Portions Copyright © 1996, Opus1, Process Software, TGV
Servers sit in a tight loop

                 socket()

                  bind()

                 listen()

                 accept()



                  read()

                 write()


                 close()

Slide 64                    Portions Copyright © 1996, Opus1, Process Software, TGV
Connectionless
                          Client/Server is simpler
 Server       socket()                            Client
                                   socket()
                bind()
                                    bind()


             recvfrom()
                                   sendto()
  block until data
  from client




              sendto()             recvfrom()




Slide 65                                  Portions Copyright © 1996, Opus1, Process Software, TGV
A socket is just
                       a data structure
                               socket

    Operating System      Protocol Family
      Channel List
                                Service
                           Local Address

                          Remote Address




Slide 66                    Portions Copyright © 1996, Opus1, Process Software, TGV
In C,
               a socket doesn’t have much

integer: always set to      socket
be PF_INET for
                         Protocol Family
TCP/IP programming                                integer: set to be
                             Service              SOCK_STREAM (TCP),
                                                  SOCK_DGRAM (UDP),
sockaddr: a 2-octet       Local Address           or SOCK_RAW (raw IP)
address family
                         Remote Address
identifier and then 14
octets of address-
specific information




Slide 67                                   Portions Copyright © 1996, Opus1, Process Software, TGV
Families and Types

     Address Families (or Protocol Families)
           AF_UNIX:      Unix domain sockets
           AF_INET:      Internet Protocols
           AF_NS:        Xerox NS Protocols
           AF_IMPLINK:   IMP link layer (obsolete)
     Types:
           SOCK_STREAM:        Stream socket (TCP)
           SOCK_DGRAM:         Datagram socket (UDP)
           SOCK_RAW:           Raw socket (IP)

Slide 68                             Portions Copyright © 1996, Opus1, Process Software, TGV
TCP/IP addresses are
                        special cases of sockaddr
              socket

           Protocol Family     struct sockaddr {
                                   u_short sa_family;
              Service
                                   char sa_data[16];
           Local Address       }

       Remote Address

                               struct sockaddr_in {
                                   u_short sin_family;
                                   u_short sin_port;
    sockaddr: a 2-octet            struct in_addr sin_addr;
    address family                 char sin_zero[8];
    identifier and then 14     }
    octets of address-
    specific information
Slide 69                                    Portions Copyright © 1996, Opus1, Process Software, TGV
sockaddr unveiled
struct sockaddr_in {
                                               sin_family: AF_INET for all TCP/IP
    u_short sin_family;
                                               addresses
    u_short sin_port;
    struct in_addr sin_addr;                    sin_port: 16-bit port number (as
    char sin_zero[8];                           used in UDP & TCP headers)
}

 sin_addr: 32-bit IP address
           /*
            * Internet address (a structure for historical reasons)
            */
           struct in_addr {
               union {
                  struct { u_char s_b1,s_b2,s_b3,s_b4; } S_un_b;
                  struct { u_short s_w1,s_w2; } S_un_w;
                  u_long S_addr;
               } S_un;
           #define s_addr S_un.S_addr



Slide 70                                                         Portions Copyright © 1996, Opus1, Process Software, TGV
Remember our goal:
                                open()
     TCP/IP socket programming is mostly
     read() and write() subroutine calls
     All of the socket routines are there to do the
     equivalent of an open() in the file system.




Slide 71                           Portions Copyright © 1996, Opus1, Process Software, TGV
Five routines are used to
                              replace the open() call
             socket            socket() : allocate socket in memory, fill in
       Protocol Family         protocol family and service fields

              Service          bind() : fill in the local address part (local
                               sockaddr). OPTIONAL for most clients
           Local Address

      Remote Address
                               listen() : tell network kernel that you want
                               to receive connects (“passive open”)
                               accept() : ask network kernel to hand you
                               the next incoming connect (“passive open”)


                               connect() : tell network kernel to connect to
                               the other side (“active open”)
Slide 72                                            Portions Copyright © 1996, Opus1, Process Software, TGV
Overview of Sockets
                                 (one more time)
     Get the socket open somehow
           socket(), bind(), listen(), accept(), connect()
     Read and write from it
           read(), write()
     When done, close the socket
           close()




Slide 73                                   Portions Copyright © 1996, Opus1, Process Software, TGV
Programming with Sockets
                          Key Concepts
     A socket is a data structure representing a
     connection
     To open a connection
           Fill in the data structure
           Link it to the network kernel
           Link it to the operating system
     Reading and writing uses the same calls as
     the file system


Slide 74                                 Portions Copyright © 1996, Opus1, Process Software, TGV
Coding with Sockets
General Flow for
                     Servers/Clients is different
Server        socket()
                                         socket()       Client

               bind()

              listen()

             accept()
  block until             connection     connect()
  connection from        establishment
  client
               read()                     write()

               write()                    read()                                  Let’s start
                                                                                  with clients
              close()                                                             because
                                          close()                                 they’re
                                                                                  easier
Slide 76                                        Portions Copyright © 1996, Opus1, Process Software, TGV
Clients
Step 1:
                                          Get Socket
socket()
            int socket(int domain, int type, int protocol);
connect()   int s, domain, type, protocol;

 write()
            domain = AF_INET;     /* always the same */
 read()
            type = SOCK_STREAM;   /* STREAM for TCP */
 close()
            protocol = 0;
            s = socket(domain, type, protocol);
            if (s < 0) ERROR(“Cannot create socket”);




Slide 78                                  Portions Copyright © 1996, Opus1, Process Software, TGV
Step 2:
            Fill in remote address fields
socket()
            #define SMTP_PORT 25
connect()   #define IP_ADDRESS 0xC0F50C02 /*192.245.12.2*/

 write()    struct sockaddr_in sin;

 read()
            sin.sin_family = AF_INET;
 close()
            sin.sin_port = htons(SMTP_PORT);
            sin.sa_addr = htonl(IP_ADDRESS);




Slide 79                                 Portions Copyright © 1996, Opus1, Process Software, TGV
Step 3:
                      Connect to other side
socket()
            int connect(int s, struct sockaddr*name, int
connect()   namelen);
            int status;
 write()

 read()     status = connect(s, (struct sockaddr*)sin,
            sizeof(sin));
 close()
            if (status != 0)
               ERROR(“Cannot connect to other side”);




Slide 80                                  Portions Copyright © 1996, Opus1, Process Software, TGV
Step 4:
                                          Use the socket
socket()    char buf[LINELEN+1];

connect()   /*
             * Now go into a loop, reading data from the network, writing
 write()     * it to the terminal and reading data from the terminal,
             * writing it to the network...
             */
 read()
            while ( (n = read(s, buf, LINELEN) ) > 0) {
 close()        fwrite(buf, n, 1, stdout);

                if (!fgets(buf, LINELEN, stdin)) break;
                write(s, buf, strlen(buf));
             }
             if (n < 0) {
                 ERROR(“Cannot read from socket!”);
            }




Slide 81                                              Portions Copyright © 1996, Opus1, Process Software, TGV
Step 5:
                 Shut it down when done
socket()
            status = close(s);
connect()   if (status != 0)
                ERROR(“Can not close socket”);
 write()

 read()

 close()




Slide 82                                  Portions Copyright © 1996, Opus1, Process Software, TGV
Servers
Server Review and
                               Overview
   socket()    socket() : allocate socket in memory, fill in
               protocol family and service fields
    bind()
               bind() : fill in the local address part (local
    listen()
               sockaddr). OPTIONAL for most clients
   accept()

    read()     listen() : tell network kernel that you want
    write()    to receive connects (“passive open”)
               accept() : ask network kernel to hand you
    close()
               the next incoming connect (“passive open”)




Slide 84                                 Portions Copyright © 1996, Opus1, Process Software, TGV
Step 1:
                                            Get Socket
   socket()
               int socket(int domain, int type, int protocol);
    bind()     int s, domain, type, protocol;
    listen()

   accept()    domain = PF_INET;     /* always the same */
               type = SOCK_STREAM;   /* STREAM for TCP */
    read()
               protocol = 0;
    write()
               s = socket(domain, type, protocol);
    close()    if (s < 0) ERROR(“Cannot create socket”);




                                         This should look vaguely
                                         familiar...
Slide 85                                    Portions Copyright © 1996, Opus1, Process Software, TGV
Step 2:
                 Fill in local address fields
   socket()
               #define SMTP_PORT 25
    bind()     #define IP_ADDRESS 0xC0F50C02 /*192.245.12.2*/
    listen()   struct sockaddr_in sin;
   accept()
               sin.sin_family = AF_INET;
    read()
               sin.sin_port = htons(SMTP_PORT);
    write()
               sin.sa_addr = INADDR_ANY;
    close()



                                         INADDR_ANY is a shorthand way of
                                         saying “I don’t care what the local
                                         address is”...
Slide 86                                        Portions Copyright © 1996, Opus1, Process Software, TGV
Step 3:
               “Bind” address to the socket
   socket()
                int bind(int s, struct sockaddr*name, int
    bind()      namelen);
                int status;
    listen()

   accept()
                status = bind(s, (struct sockaddr*)sin,
    read()      sizeof(sin));

    write()     if (status != 0)
                   ERROR(“Cannot bind to local address”);
    close()



                                       INADDR_ANY is a shorthand way of
                                       saying “I don’t care what the local
                                       address is”...
Slide 87                                      Portions Copyright © 1996, Opus1, Process Software, TGV
Step 4:
                      Tell the kernel to listen
   socket()
               #define MAX_BACKLOG 5
    bind()     int listen(int s, int backlog);
    listen()   int status;
   accept()
               status = listen(s, MAX_BACKLOG);
    read()
               if (status != 0)
    write()
                  ERROR(“Cannot ask kernel to listen”);
    close()




Slide 88                                    Portions Copyright © 1996, Opus1, Process Software, TGV
Step 5:
                 Block waiting for connect
   socket()
               int accept(int s, struct sockaddr *addr, int
    bind()     *addrlen);
               int status, addrlen, vs;
    listen()
               struct sockaddr_in sin2;
   accept()

    read()
               addrlen = sizeof(sin2);
    write()    vs = accept(s, (struct sockaddr*)&sin2,
               &addrlen);
    close()
               if (vs < 0)
                  ERROR(“Cannot accept a connection.”);




Slide 89                                    Portions Copyright © 1996, Opus1, Process Software, TGV
Step 6:
                                          Read and Write
   socket()
               /* Get the line from the client. */
                        read ( vs, buf, 256 );
    bind()
               /* Translate the logical name. */
    listen()            log_name = getenv ( buf );

   accept()    /* Get the definition string and add a new line to it. */
                        sprintf ( buf, quot;%snquot;, log_name );
    read()
               /* Write the translation to the client. */
                        write ( vs, buf, strlen ( buf ) );
    write()

    close()



                                             Yes, this code has lots of holes in it.
                                             But you get the picture of what we’re
                                             trying to do.
Slide 90                                             Portions Copyright © 1996, Opus1, Process Software, TGV
Step 7:
                        Tear down when done
   socket()
               status = close(s);
    bind()     if (status != 0)
                   ERROR(“Can not close socket”);
    listen()

   accept()

    read()

    write()

    close()




Slide 91                                     Portions Copyright © 1996, Opus1, Process Software, TGV
Of course, there are more
                         routines than those
socket          Create a descriptor for use in network communication
connect         Connect to a remote peer (client)
write           Send outgoing data across a connection
read            Acquire incoming data from a connection
close           Terminate communication and deallocate a descriptor
bind            Bind a local IP address and protocol port to a socket
listen          Place the socket in passive mode and set backlog
accept          Accept the next incoming connection (server)
recv, recvmsg   Receive the next incoming datagram
recvfrom        Receive the next incoming datagram and record source addr.
send, sendmsg   Send an outgoing datagram
sendto          Send an outgoing datagram to a particular dest. addr.
shutdown        Terminate a TCP connection in one or both directions
getpeername     After a connection arrives, obtain remote machine’s address
getsockopt      Obtain the current options for a socket
setsockopt      Change the options for a socket

Slide 92                                             Portions Copyright © 1996, Opus1, Process Software, TGV
Coding with Sockets
                               Key Concepts
     All clients and servers basically look the
     same
     Follow a template, but make sure you
     understand what you’re doing
           Lots of templates are wrong
           Lots of templates don’t do what you think they
           do




Slide 93                                Portions Copyright © 1996, Opus1, Process Software, TGV

Weitere ähnliche Inhalte

Was ist angesagt?

CCNP Switching Chapter 1
CCNP Switching Chapter 1CCNP Switching Chapter 1
CCNP Switching Chapter 1Chaing Ravuth
 
The linux networking architecture
The linux networking architectureThe linux networking architecture
The linux networking architecturehugo lu
 
Dhcp presentation
Dhcp presentationDhcp presentation
Dhcp presentationSaqib Malik
 
Types of interfaces in a Cisco Router
Types of interfaces in a Cisco RouterTypes of interfaces in a Cisco Router
Types of interfaces in a Cisco RouterNetProtocol Xpert
 
Tutorial WiFi driver code - Opening Nuts and Bolts of Linux WiFi Subsystem
Tutorial WiFi driver code - Opening Nuts and Bolts of Linux WiFi SubsystemTutorial WiFi driver code - Opening Nuts and Bolts of Linux WiFi Subsystem
Tutorial WiFi driver code - Opening Nuts and Bolts of Linux WiFi SubsystemDheryta Jaisinghani
 
Sockets in unix
Sockets in unixSockets in unix
Sockets in unixswtjerin4u
 
Unicast multicast & broadcast
Unicast multicast & broadcastUnicast multicast & broadcast
Unicast multicast & broadcastNetProtocol Xpert
 
VLAN, VTP, DTP, Ether channel Cheat Sheet With examples.pptx
VLAN, VTP, DTP, Ether channel  Cheat Sheet With examples.pptxVLAN, VTP, DTP, Ether channel  Cheat Sheet With examples.pptx
VLAN, VTP, DTP, Ether channel Cheat Sheet With examples.pptxINFitunes
 
Internet control message protocol
Internet control message protocolInternet control message protocol
Internet control message protocolasimnawaz54
 
Tcp Udp Icmp And The Transport Layer
Tcp Udp Icmp And The Transport LayerTcp Udp Icmp And The Transport Layer
Tcp Udp Icmp And The Transport Layertmavroidis
 
Socket programming or network programming
Socket programming or network programmingSocket programming or network programming
Socket programming or network programmingMmanan91
 

Was ist angesagt? (20)

IEEE 802.11
IEEE 802.11IEEE 802.11
IEEE 802.11
 
Subnetting
SubnettingSubnetting
Subnetting
 
CCNP Switching Chapter 1
CCNP Switching Chapter 1CCNP Switching Chapter 1
CCNP Switching Chapter 1
 
The linux networking architecture
The linux networking architectureThe linux networking architecture
The linux networking architecture
 
Dhcp presentation
Dhcp presentationDhcp presentation
Dhcp presentation
 
Types of interfaces in a Cisco Router
Types of interfaces in a Cisco RouterTypes of interfaces in a Cisco Router
Types of interfaces in a Cisco Router
 
Tutorial WiFi driver code - Opening Nuts and Bolts of Linux WiFi Subsystem
Tutorial WiFi driver code - Opening Nuts and Bolts of Linux WiFi SubsystemTutorial WiFi driver code - Opening Nuts and Bolts of Linux WiFi Subsystem
Tutorial WiFi driver code - Opening Nuts and Bolts of Linux WiFi Subsystem
 
Telnet & SSH
Telnet & SSHTelnet & SSH
Telnet & SSH
 
Dhcp ppt
Dhcp pptDhcp ppt
Dhcp ppt
 
Sockets in unix
Sockets in unixSockets in unix
Sockets in unix
 
IPV6 INTRODUCTION
IPV6 INTRODUCTIONIPV6 INTRODUCTION
IPV6 INTRODUCTION
 
Unicast multicast & broadcast
Unicast multicast & broadcastUnicast multicast & broadcast
Unicast multicast & broadcast
 
VLAN, VTP, DTP, Ether channel Cheat Sheet With examples.pptx
VLAN, VTP, DTP, Ether channel  Cheat Sheet With examples.pptxVLAN, VTP, DTP, Ether channel  Cheat Sheet With examples.pptx
VLAN, VTP, DTP, Ether channel Cheat Sheet With examples.pptx
 
CCNA ppt
CCNA pptCCNA ppt
CCNA ppt
 
Internet control message protocol
Internet control message protocolInternet control message protocol
Internet control message protocol
 
IPv6
IPv6IPv6
IPv6
 
IP Routing
IP RoutingIP Routing
IP Routing
 
Tcp Udp Icmp And The Transport Layer
Tcp Udp Icmp And The Transport LayerTcp Udp Icmp And The Transport Layer
Tcp Udp Icmp And The Transport Layer
 
Bgp protocol
Bgp protocolBgp protocol
Bgp protocol
 
Socket programming or network programming
Socket programming or network programmingSocket programming or network programming
Socket programming or network programming
 

Andere mochten auch

Andere mochten auch (20)

Socket Programming Tutorial
Socket Programming TutorialSocket Programming Tutorial
Socket Programming Tutorial
 
Socket programming
Socket programmingSocket programming
Socket programming
 
Aula sockets
Aula socketsAula sockets
Aula sockets
 
Sockets
SocketsSockets
Sockets
 
Lidando com Erros - Android
Lidando com Erros - AndroidLidando com Erros - Android
Lidando com Erros - Android
 
Network programming
Network programmingNetwork programming
Network programming
 
Pyhug zmq
Pyhug zmqPyhug zmq
Pyhug zmq
 
Aulas de Java Avançado 2- Faculdade iDez 2010
Aulas de Java Avançado 2- Faculdade iDez 2010Aulas de Java Avançado 2- Faculdade iDez 2010
Aulas de Java Avançado 2- Faculdade iDez 2010
 
Aplicações Web Ricas e Acessíveis
Aplicações Web Ricas e AcessíveisAplicações Web Ricas e Acessíveis
Aplicações Web Ricas e Acessíveis
 
Linguagem PHP
Linguagem PHPLinguagem PHP
Linguagem PHP
 
Chalet management system (e cha m)
Chalet management system (e cha m)Chalet management system (e cha m)
Chalet management system (e cha m)
 
Linguagem PHP para principiantes
Linguagem PHP para principiantesLinguagem PHP para principiantes
Linguagem PHP para principiantes
 
Módulo-6-7-ip-com-sockets
Módulo-6-7-ip-com-socketsMódulo-6-7-ip-com-sockets
Módulo-6-7-ip-com-sockets
 
Tecnologia java para sockets
Tecnologia java para socketsTecnologia java para sockets
Tecnologia java para sockets
 
TCP/IP basics
TCP/IP basicsTCP/IP basics
TCP/IP basics
 
Building High Performance Scalable TCP/IP Servers with Apache MINA
Building High Performance Scalable TCP/IP Servers with Apache MINABuilding High Performance Scalable TCP/IP Servers with Apache MINA
Building High Performance Scalable TCP/IP Servers with Apache MINA
 
A Short Java Socket Tutorial
A Short Java Socket TutorialA Short Java Socket Tutorial
A Short Java Socket Tutorial
 
Redes 1 - Sockets em C#
Redes 1 - Sockets em C#Redes 1 - Sockets em C#
Redes 1 - Sockets em C#
 
Socket programming using java
Socket programming using javaSocket programming using java
Socket programming using java
 
Tftp client server communication
Tftp client server communicationTftp client server communication
Tftp client server communication
 

Ähnlich wie Programming TCP/IP with Sockets

Ähnlich wie Programming TCP/IP with Sockets (20)

Np unit2
Np unit2Np unit2
Np unit2
 
اسلاید اول جلسه یازدهم کلاس پایتون برای هکرهای قانونی
اسلاید اول جلسه یازدهم کلاس پایتون برای هکرهای قانونیاسلاید اول جلسه یازدهم کلاس پایتون برای هکرهای قانونی
اسلاید اول جلسه یازدهم کلاس پایتون برای هکرهای قانونی
 
Linux Network Management
Linux Network ManagementLinux Network Management
Linux Network Management
 
Symbian OS - Communication And Messaging
Symbian OS - Communication And MessagingSymbian OS - Communication And Messaging
Symbian OS - Communication And Messaging
 
Network Sockets
Network SocketsNetwork Sockets
Network Sockets
 
Sockets
Sockets Sockets
Sockets
 
Socket Programming TCP:IP PPT.pdf
Socket Programming TCP:IP PPT.pdfSocket Programming TCP:IP PPT.pdf
Socket Programming TCP:IP PPT.pdf
 
Python networking
Python networkingPython networking
Python networking
 
An analysis of the skype peer to-peer
An analysis of the skype peer to-peerAn analysis of the skype peer to-peer
An analysis of the skype peer to-peer
 
CCNA Interview.pdf
CCNA Interview.pdfCCNA Interview.pdf
CCNA Interview.pdf
 
2014/09/02 Cisco UCS HPC @ ANL
2014/09/02 Cisco UCS HPC @ ANL2014/09/02 Cisco UCS HPC @ ANL
2014/09/02 Cisco UCS HPC @ ANL
 
Sockets intro
Sockets introSockets intro
Sockets intro
 
internet services
internet servicesinternet services
internet services
 
Network Drivers
Network DriversNetwork Drivers
Network Drivers
 
Advanced RAC troubleshooting: Network
Advanced RAC troubleshooting: NetworkAdvanced RAC troubleshooting: Network
Advanced RAC troubleshooting: Network
 
GREAT MINDS
GREAT MINDSGREAT MINDS
GREAT MINDS
 
Chapter_3_Networking.ppt
Chapter_3_Networking.pptChapter_3_Networking.ppt
Chapter_3_Networking.ppt
 
Chapter_3_Networking.ppt
Chapter_3_Networking.pptChapter_3_Networking.ppt
Chapter_3_Networking.ppt
 
Putting an Apple IIgs BBS on the internet
Putting an Apple IIgs BBS on the internetPutting an Apple IIgs BBS on the internet
Putting an Apple IIgs BBS on the internet
 
6lowpan
6lowpan6lowpan
6lowpan
 

Mehr von elliando dias

Clojurescript slides
Clojurescript slidesClojurescript slides
Clojurescript slideselliando dias
 
Why you should be excited about ClojureScript
Why you should be excited about ClojureScriptWhy you should be excited about ClojureScript
Why you should be excited about ClojureScriptelliando dias
 
Functional Programming with Immutable Data Structures
Functional Programming with Immutable Data StructuresFunctional Programming with Immutable Data Structures
Functional Programming with Immutable Data Structureselliando dias
 
Nomenclatura e peças de container
Nomenclatura  e peças de containerNomenclatura  e peças de container
Nomenclatura e peças de containerelliando dias
 
Polyglot and Poly-paradigm Programming for Better Agility
Polyglot and Poly-paradigm Programming for Better AgilityPolyglot and Poly-paradigm Programming for Better Agility
Polyglot and Poly-paradigm Programming for Better Agilityelliando dias
 
Javascript Libraries
Javascript LibrariesJavascript Libraries
Javascript Librarieselliando dias
 
How to Make an Eight Bit Computer and Save the World!
How to Make an Eight Bit Computer and Save the World!How to Make an Eight Bit Computer and Save the World!
How to Make an Eight Bit Computer and Save the World!elliando dias
 
A Practical Guide to Connecting Hardware to the Web
A Practical Guide to Connecting Hardware to the WebA Practical Guide to Connecting Hardware to the Web
A Practical Guide to Connecting Hardware to the Webelliando dias
 
Introdução ao Arduino
Introdução ao ArduinoIntrodução ao Arduino
Introdução ao Arduinoelliando dias
 
Incanter Data Sorcery
Incanter Data SorceryIncanter Data Sorcery
Incanter Data Sorceryelliando dias
 
Fab.in.a.box - Fab Academy: Machine Design
Fab.in.a.box - Fab Academy: Machine DesignFab.in.a.box - Fab Academy: Machine Design
Fab.in.a.box - Fab Academy: Machine Designelliando dias
 
The Digital Revolution: Machines that makes
The Digital Revolution: Machines that makesThe Digital Revolution: Machines that makes
The Digital Revolution: Machines that makeselliando dias
 
Hadoop - Simple. Scalable.
Hadoop - Simple. Scalable.Hadoop - Simple. Scalable.
Hadoop - Simple. Scalable.elliando dias
 
Hadoop and Hive Development at Facebook
Hadoop and Hive Development at FacebookHadoop and Hive Development at Facebook
Hadoop and Hive Development at Facebookelliando dias
 
Multi-core Parallelization in Clojure - a Case Study
Multi-core Parallelization in Clojure - a Case StudyMulti-core Parallelization in Clojure - a Case Study
Multi-core Parallelization in Clojure - a Case Studyelliando dias
 

Mehr von elliando dias (20)

Clojurescript slides
Clojurescript slidesClojurescript slides
Clojurescript slides
 
Why you should be excited about ClojureScript
Why you should be excited about ClojureScriptWhy you should be excited about ClojureScript
Why you should be excited about ClojureScript
 
Functional Programming with Immutable Data Structures
Functional Programming with Immutable Data StructuresFunctional Programming with Immutable Data Structures
Functional Programming with Immutable Data Structures
 
Nomenclatura e peças de container
Nomenclatura  e peças de containerNomenclatura  e peças de container
Nomenclatura e peças de container
 
Geometria Projetiva
Geometria ProjetivaGeometria Projetiva
Geometria Projetiva
 
Polyglot and Poly-paradigm Programming for Better Agility
Polyglot and Poly-paradigm Programming for Better AgilityPolyglot and Poly-paradigm Programming for Better Agility
Polyglot and Poly-paradigm Programming for Better Agility
 
Javascript Libraries
Javascript LibrariesJavascript Libraries
Javascript Libraries
 
How to Make an Eight Bit Computer and Save the World!
How to Make an Eight Bit Computer and Save the World!How to Make an Eight Bit Computer and Save the World!
How to Make an Eight Bit Computer and Save the World!
 
Ragel talk
Ragel talkRagel talk
Ragel talk
 
A Practical Guide to Connecting Hardware to the Web
A Practical Guide to Connecting Hardware to the WebA Practical Guide to Connecting Hardware to the Web
A Practical Guide to Connecting Hardware to the Web
 
Introdução ao Arduino
Introdução ao ArduinoIntrodução ao Arduino
Introdução ao Arduino
 
Minicurso arduino
Minicurso arduinoMinicurso arduino
Minicurso arduino
 
Incanter Data Sorcery
Incanter Data SorceryIncanter Data Sorcery
Incanter Data Sorcery
 
Rango
RangoRango
Rango
 
Fab.in.a.box - Fab Academy: Machine Design
Fab.in.a.box - Fab Academy: Machine DesignFab.in.a.box - Fab Academy: Machine Design
Fab.in.a.box - Fab Academy: Machine Design
 
The Digital Revolution: Machines that makes
The Digital Revolution: Machines that makesThe Digital Revolution: Machines that makes
The Digital Revolution: Machines that makes
 
Hadoop + Clojure
Hadoop + ClojureHadoop + Clojure
Hadoop + Clojure
 
Hadoop - Simple. Scalable.
Hadoop - Simple. Scalable.Hadoop - Simple. Scalable.
Hadoop - Simple. Scalable.
 
Hadoop and Hive Development at Facebook
Hadoop and Hive Development at FacebookHadoop and Hive Development at Facebook
Hadoop and Hive Development at Facebook
 
Multi-core Parallelization in Clojure - a Case Study
Multi-core Parallelization in Clojure - a Case StudyMulti-core Parallelization in Clojure - a Case Study
Multi-core Parallelization in Clojure - a Case Study
 

Kürzlich hochgeladen

DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Angeliki Cooney
 

Kürzlich hochgeladen (20)

DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 

Programming TCP/IP with Sockets

  • 1. Session NM056 Programming TCP/IP with Sockets Geoff Bryant Process software
  • 2. Course Roadmap NM055 (11:00-12:00) Important Terms and Concepts TCP/IP and Client/Server Model Sockets and TLI Client/Server in TCP/IP NM056 (1:00-2:00) Socket Routines NM057 (2:00-3:00) Library Routines NM058 (3:00-4:00) Sample Client/Server NM059 (4:00-5:00) VMS specifics (QIOs) NM067 (6:00-7:00) Clinic - Q&A Slide 57 Portions Copyright © 1996, Opus1, Process Software, TGV
  • 3. TCP/IP Programming Slides and Source Code available via anonymous FTP: Host:: ftp.process.com Directory: [pub.decus] Slides: DECUS_F96_PROG.PS Examples: DECUS_F96_PROG_EXAMPLES.TXT Host: ftp.opus1.com Slides: DECUS_F96_PROG.PS Examples: DECUS_F96_PROG_EXAMPLES.TXT Slide 58 Portions Copyright © 1996, Opus1, Process Software, TGV
  • 4. Programming with Sockets Roadmap Berkeley Socket History Overview of the Socket Paradigm Socket addresses Other programming models Slide 59 Portions Copyright © 1996, Opus1, Process Software, TGV
  • 5. Berkeley Socket History Documented in such books as Stevens’s Unix Network Programming Comer’s Internetworking with TCP/IP, vol III First provided with Berkeley Software Distribution (BSD 4.1c) Unix for the VAX Popularized in the 1986 4.3BSD release Slide 60 Portions Copyright © 1996, Opus1, Process Software, TGV
  • 6. Other Programming Models Socket model is widely used mainly due to wide implementation of BSD networking kernel Avaible for Unix, Windows, VMS, ... Other models may be used in different environments STREAMS model (UNIX System V) Others Slide 61 Portions Copyright © 1996, Opus1, Process Software, TGV
  • 7. Socket Paradigm Overview A socket is a communications endpoint In BSD networking, it is a data structure within the kernel A socket is “named” by its socket address A connection is represented by two communicating sockets Slide 62 Portions Copyright © 1996, Opus1, Process Software, TGV
  • 8. Using sockets is like using the file system Server socket() Client socket() bind() listen() accept() block until connection connect() connection from establishment client read() write() write() read() close() close() Slide 63 Portions Copyright © 1996, Opus1, Process Software, TGV
  • 9. Servers sit in a tight loop socket() bind() listen() accept() read() write() close() Slide 64 Portions Copyright © 1996, Opus1, Process Software, TGV
  • 10. Connectionless Client/Server is simpler Server socket() Client socket() bind() bind() recvfrom() sendto() block until data from client sendto() recvfrom() Slide 65 Portions Copyright © 1996, Opus1, Process Software, TGV
  • 11. A socket is just a data structure socket Operating System Protocol Family Channel List Service Local Address Remote Address Slide 66 Portions Copyright © 1996, Opus1, Process Software, TGV
  • 12. In C, a socket doesn’t have much integer: always set to socket be PF_INET for Protocol Family TCP/IP programming integer: set to be Service SOCK_STREAM (TCP), SOCK_DGRAM (UDP), sockaddr: a 2-octet Local Address or SOCK_RAW (raw IP) address family Remote Address identifier and then 14 octets of address- specific information Slide 67 Portions Copyright © 1996, Opus1, Process Software, TGV
  • 13. Families and Types Address Families (or Protocol Families) AF_UNIX: Unix domain sockets AF_INET: Internet Protocols AF_NS: Xerox NS Protocols AF_IMPLINK: IMP link layer (obsolete) Types: SOCK_STREAM: Stream socket (TCP) SOCK_DGRAM: Datagram socket (UDP) SOCK_RAW: Raw socket (IP) Slide 68 Portions Copyright © 1996, Opus1, Process Software, TGV
  • 14. TCP/IP addresses are special cases of sockaddr socket Protocol Family struct sockaddr { u_short sa_family; Service char sa_data[16]; Local Address } Remote Address struct sockaddr_in { u_short sin_family; u_short sin_port; sockaddr: a 2-octet struct in_addr sin_addr; address family char sin_zero[8]; identifier and then 14 } octets of address- specific information Slide 69 Portions Copyright © 1996, Opus1, Process Software, TGV
  • 15. sockaddr unveiled struct sockaddr_in { sin_family: AF_INET for all TCP/IP u_short sin_family; addresses u_short sin_port; struct in_addr sin_addr; sin_port: 16-bit port number (as char sin_zero[8]; used in UDP & TCP headers) } sin_addr: 32-bit IP address /* * Internet address (a structure for historical reasons) */ struct in_addr { union { struct { u_char s_b1,s_b2,s_b3,s_b4; } S_un_b; struct { u_short s_w1,s_w2; } S_un_w; u_long S_addr; } S_un; #define s_addr S_un.S_addr Slide 70 Portions Copyright © 1996, Opus1, Process Software, TGV
  • 16. Remember our goal: open() TCP/IP socket programming is mostly read() and write() subroutine calls All of the socket routines are there to do the equivalent of an open() in the file system. Slide 71 Portions Copyright © 1996, Opus1, Process Software, TGV
  • 17. Five routines are used to replace the open() call socket socket() : allocate socket in memory, fill in Protocol Family protocol family and service fields Service bind() : fill in the local address part (local sockaddr). OPTIONAL for most clients Local Address Remote Address listen() : tell network kernel that you want to receive connects (“passive open”) accept() : ask network kernel to hand you the next incoming connect (“passive open”) connect() : tell network kernel to connect to the other side (“active open”) Slide 72 Portions Copyright © 1996, Opus1, Process Software, TGV
  • 18. Overview of Sockets (one more time) Get the socket open somehow socket(), bind(), listen(), accept(), connect() Read and write from it read(), write() When done, close the socket close() Slide 73 Portions Copyright © 1996, Opus1, Process Software, TGV
  • 19. Programming with Sockets Key Concepts A socket is a data structure representing a connection To open a connection Fill in the data structure Link it to the network kernel Link it to the operating system Reading and writing uses the same calls as the file system Slide 74 Portions Copyright © 1996, Opus1, Process Software, TGV
  • 21. General Flow for Servers/Clients is different Server socket() socket() Client bind() listen() accept() block until connection connect() connection from establishment client read() write() write() read() Let’s start with clients close() because close() they’re easier Slide 76 Portions Copyright © 1996, Opus1, Process Software, TGV
  • 23. Step 1: Get Socket socket() int socket(int domain, int type, int protocol); connect() int s, domain, type, protocol; write() domain = AF_INET; /* always the same */ read() type = SOCK_STREAM; /* STREAM for TCP */ close() protocol = 0; s = socket(domain, type, protocol); if (s < 0) ERROR(“Cannot create socket”); Slide 78 Portions Copyright © 1996, Opus1, Process Software, TGV
  • 24. Step 2: Fill in remote address fields socket() #define SMTP_PORT 25 connect() #define IP_ADDRESS 0xC0F50C02 /*192.245.12.2*/ write() struct sockaddr_in sin; read() sin.sin_family = AF_INET; close() sin.sin_port = htons(SMTP_PORT); sin.sa_addr = htonl(IP_ADDRESS); Slide 79 Portions Copyright © 1996, Opus1, Process Software, TGV
  • 25. Step 3: Connect to other side socket() int connect(int s, struct sockaddr*name, int connect() namelen); int status; write() read() status = connect(s, (struct sockaddr*)sin, sizeof(sin)); close() if (status != 0) ERROR(“Cannot connect to other side”); Slide 80 Portions Copyright © 1996, Opus1, Process Software, TGV
  • 26. Step 4: Use the socket socket() char buf[LINELEN+1]; connect() /* * Now go into a loop, reading data from the network, writing write() * it to the terminal and reading data from the terminal, * writing it to the network... */ read() while ( (n = read(s, buf, LINELEN) ) > 0) { close() fwrite(buf, n, 1, stdout); if (!fgets(buf, LINELEN, stdin)) break; write(s, buf, strlen(buf)); } if (n < 0) { ERROR(“Cannot read from socket!”); } Slide 81 Portions Copyright © 1996, Opus1, Process Software, TGV
  • 27. Step 5: Shut it down when done socket() status = close(s); connect() if (status != 0) ERROR(“Can not close socket”); write() read() close() Slide 82 Portions Copyright © 1996, Opus1, Process Software, TGV
  • 29. Server Review and Overview socket() socket() : allocate socket in memory, fill in protocol family and service fields bind() bind() : fill in the local address part (local listen() sockaddr). OPTIONAL for most clients accept() read() listen() : tell network kernel that you want write() to receive connects (“passive open”) accept() : ask network kernel to hand you close() the next incoming connect (“passive open”) Slide 84 Portions Copyright © 1996, Opus1, Process Software, TGV
  • 30. Step 1: Get Socket socket() int socket(int domain, int type, int protocol); bind() int s, domain, type, protocol; listen() accept() domain = PF_INET; /* always the same */ type = SOCK_STREAM; /* STREAM for TCP */ read() protocol = 0; write() s = socket(domain, type, protocol); close() if (s < 0) ERROR(“Cannot create socket”); This should look vaguely familiar... Slide 85 Portions Copyright © 1996, Opus1, Process Software, TGV
  • 31. Step 2: Fill in local address fields socket() #define SMTP_PORT 25 bind() #define IP_ADDRESS 0xC0F50C02 /*192.245.12.2*/ listen() struct sockaddr_in sin; accept() sin.sin_family = AF_INET; read() sin.sin_port = htons(SMTP_PORT); write() sin.sa_addr = INADDR_ANY; close() INADDR_ANY is a shorthand way of saying “I don’t care what the local address is”... Slide 86 Portions Copyright © 1996, Opus1, Process Software, TGV
  • 32. Step 3: “Bind” address to the socket socket() int bind(int s, struct sockaddr*name, int bind() namelen); int status; listen() accept() status = bind(s, (struct sockaddr*)sin, read() sizeof(sin)); write() if (status != 0) ERROR(“Cannot bind to local address”); close() INADDR_ANY is a shorthand way of saying “I don’t care what the local address is”... Slide 87 Portions Copyright © 1996, Opus1, Process Software, TGV
  • 33. Step 4: Tell the kernel to listen socket() #define MAX_BACKLOG 5 bind() int listen(int s, int backlog); listen() int status; accept() status = listen(s, MAX_BACKLOG); read() if (status != 0) write() ERROR(“Cannot ask kernel to listen”); close() Slide 88 Portions Copyright © 1996, Opus1, Process Software, TGV
  • 34. Step 5: Block waiting for connect socket() int accept(int s, struct sockaddr *addr, int bind() *addrlen); int status, addrlen, vs; listen() struct sockaddr_in sin2; accept() read() addrlen = sizeof(sin2); write() vs = accept(s, (struct sockaddr*)&sin2, &addrlen); close() if (vs < 0) ERROR(“Cannot accept a connection.”); Slide 89 Portions Copyright © 1996, Opus1, Process Software, TGV
  • 35. Step 6: Read and Write socket() /* Get the line from the client. */ read ( vs, buf, 256 ); bind() /* Translate the logical name. */ listen() log_name = getenv ( buf ); accept() /* Get the definition string and add a new line to it. */ sprintf ( buf, quot;%snquot;, log_name ); read() /* Write the translation to the client. */ write ( vs, buf, strlen ( buf ) ); write() close() Yes, this code has lots of holes in it. But you get the picture of what we’re trying to do. Slide 90 Portions Copyright © 1996, Opus1, Process Software, TGV
  • 36. Step 7: Tear down when done socket() status = close(s); bind() if (status != 0) ERROR(“Can not close socket”); listen() accept() read() write() close() Slide 91 Portions Copyright © 1996, Opus1, Process Software, TGV
  • 37. Of course, there are more routines than those socket Create a descriptor for use in network communication connect Connect to a remote peer (client) write Send outgoing data across a connection read Acquire incoming data from a connection close Terminate communication and deallocate a descriptor bind Bind a local IP address and protocol port to a socket listen Place the socket in passive mode and set backlog accept Accept the next incoming connection (server) recv, recvmsg Receive the next incoming datagram recvfrom Receive the next incoming datagram and record source addr. send, sendmsg Send an outgoing datagram sendto Send an outgoing datagram to a particular dest. addr. shutdown Terminate a TCP connection in one or both directions getpeername After a connection arrives, obtain remote machine’s address getsockopt Obtain the current options for a socket setsockopt Change the options for a socket Slide 92 Portions Copyright © 1996, Opus1, Process Software, TGV
  • 38. Coding with Sockets Key Concepts All clients and servers basically look the same Follow a template, but make sure you understand what you’re doing Lots of templates are wrong Lots of templates don’t do what you think they do Slide 93 Portions Copyright © 1996, Opus1, Process Software, TGV