SlideShare ist ein Scribd-Unternehmen logo
1 von 20
Downloaden Sie, um offline zu lesen
Socket Programming

          Srinidhi Varadarajan
Client-server paradigm
Client:
                                   application
                                   transport
   initiates contact with server    network
                                    data link
   (“speaks first”)                 physical

   typically requests service                    request
   from server,
   for Web, client is
   implemented in browser; for
   e-mail, in mail reader
                                                           reply
Server:
   provides requested service                              application
                                                           transport
   to client                                                network
                                                            data link
                                                            physical
   e.g., Web server sends
   requested Web page, mail
   server delivers e-mail
Application Layer Programming

API: application programming interface
 defines interface between application and
 transport layer

 sockets: Internet API
  – two processes communicate by sending data
    into socket, reading data out of socket
Socket Interface. What is it?
 Gives a file system like abstraction to the
 capabilities of the network.

 Each transport protocol offers a set of
 services. The socket API provides the
 abstraction to access these services

 The API defines function calls to create,
 close, read and write to/from a socket.
Socket Abstraction
 The socket is the basic abstraction for network
 communication in the socket API
  – Defines an endpoint of communication for a process
  – Operating system maintains information about the
    socket and its connection
  – Application references the socket for sends, receives,
    etc.


                       Network
         Process                      Process
            A                            B

                   Ports (Sockets)
What do you need for socket communication ?

    Basically 4 parameters
    –   Source Identifier (IP address)
    –   Source Port
    –   Destination Identifier
    –   Destination Port


    In the socket API, this information is
    communicated by binding the socket.
Creating a socket
 int socket(int domain, int type, int protocol)


Protocol Family:                     Usually
  PF_INET or                         UNSPEC
   PF_UNIX

                     Communication
                       semantics:
                   SOCK_STREAM or
                    SOCK_DGRAM


The call returns a integer identifier called a
  handle
Binding a socket
int bind (int socket, struct sockaddr *address, int addr_len)



  This call is executed by:
   – Server in TCP and UDP


  It binds the socket to the specified address. The
  address parameter specifies the local component
  of the address, e.g. IP address and UDP/TCP port
Socket Descriptors
 Operating system maintains a set of
 socket descriptors for each process
 – Note that socket descriptors are shared
   by threads
 Three data structures
 – Socket descriptor table
 – Socket data structure
 – Address data structure
Socket Descriptors
  Socket        Socket Data
 Descriptor      Structure
   Table      proto family:
0:            PF_INET
                                 Address Data
1:            service:            Structure
2:            SOCK_STREAM
                                address family:
      .
      .       local address:
      .                         AF_INET
              remote address:   host IP:
                                128.173.88.85
                      .
                      .
                      .         port:
                                80
TCP Server Side: Listen
int listen (int socket, int backlog)


 This server side call specifies the number
 of pending connections on the given
 socket.

 When the server is processing a
 connection, “backlog” number of
 connections may be pending in a queue.
TCP Server Side: Passive Open
int accept (int socket, struct sockaddr *address, int *addr_len)


   This call is executed by the server.

   The call does not return until a remote
   client has established a connection.

   When it completes, it returns a new socket
   handle corresponding to the just-
   established connection
TCP Client Side: Active Open
int connect (int socket, struct sockaddr *address, int *addr_len)

   This call is executed by the client. *address
   contains the remote address.

   The call attempts to connect the socket to a
   server. It does not return until a connection has
   been established.

   When the call completes, the socket “socket” is
   connected and ready for communication.
Sockets: Summary
   Client:
int socket(int domain, int type, int protocol)
int connect (int socket, struct sockaddr *address, int addr_len)


   Server:
int socket(int domain, int type, int protocol)
int bind (int socket, struct sockaddr *address, int addr_len)
int listen (int socket, int backlog)
int accept (int socket, struct sockaddr *address, int *addr_len)
Message Passing
 int send (int socket, char *message, int msg_len, int
           flags) (TCP)
 int sendto (int socket, void *msg, int len, int
             flags, struct sockaddr * to,
             int tolen ); (UDP)
 int write(int socket, void *msg, int len); /* TCP */


 int recv (int socket, char *buffer,   int buf_len, int
           flags) (TCP)
 int recvfrom(int socket, void *msg,   int len, int
              flags, struct sockaddr   *from, int
              *fromlen); (UDP)
 int read(int socket, void *msg, int   len); (TCP)
Summary of Basic Socket Calls
    CLIENT        Connect      SERVER
             (3-way handshake)
   connect()                   accept()




                                          new connection
    write()       Data         read()


     read()       Data         write()


    close()                    close()
Network Byte Order
 Network byte order is most-significant
 byte first
 Byte ordering at a host may differ
 Utility functions
 – htons(): Host-to-network byte order for a short
   word (2 bytes)
 – htonl(): Host-to-network byte order for a long
   word (4 bytes)
 – ntohs(): Network-to-host byte order for a short
   word
 – ntohl(): Network-to-host byte order for a long
   word
Some Other “Utility” Functions
 gethostname() -- get name of local host
 getpeername() -- get address of remote
 host
 getsockname() -- get local address of
 socket
 getXbyY() -- get protocol, host, or service
 number using known number, address, or
 port, respectively
 getsockopt() -- get current socket options
 setsockopt() -- set socket options
 ioctl() -- retrieve or set socket information
Some Other “Utility” Functions
 inet_addr() -- convert “dotted”
 character string form of IP address to
 internal binary form
 inet_ntoa() -- convert internal binary
 form of IP address to “dotted”
 character string form
Address Data Structures
struct sockaddr {
  u_short    sa_family;       // type of address
  char       sa_data[14];     // value of address
}

  sockaddr is a generic address structure

struct sockaddr_in {
  u_short    sa_family;        // type of address (AF_INET)
  u_short    sa_port;          // protocol port number
  struct     in_addr sin_addr;          // IP address
  char       sin_zero[8];      // unused (set to zero)
}
   sockaddr_in is specific instance for the Internet address
   family

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (20)

Sockets
SocketsSockets
Sockets
 
Socket programming
Socket programmingSocket programming
Socket programming
 
Socket programming using C
Socket programming using CSocket programming using C
Socket programming using C
 
Socket programming
Socket programmingSocket programming
Socket programming
 
What is Socket Programming in Python | Edureka
What is Socket Programming in Python | EdurekaWhat is Socket Programming in Python | Edureka
What is Socket Programming in Python | Edureka
 
Java Socket Programming
Java Socket ProgrammingJava Socket Programming
Java Socket Programming
 
Socket programming
Socket programming Socket programming
Socket programming
 
Socket programming in python
Socket programming in pythonSocket programming in python
Socket programming in python
 
Socket programming
Socket programmingSocket programming
Socket programming
 
Socket programming
Socket programmingSocket programming
Socket programming
 
Java socket programming
Java socket programmingJava socket programming
Java socket programming
 
Np unit2
Np unit2Np unit2
Np unit2
 
Network programming in Java
Network programming in JavaNetwork programming in Java
Network programming in Java
 
Tcp/ip server sockets
Tcp/ip server socketsTcp/ip server sockets
Tcp/ip server sockets
 
Network security Lab manual
Network security Lab manual Network security Lab manual
Network security Lab manual
 
Application layer protocols
Application layer protocolsApplication layer protocols
Application layer protocols
 
Servlets
ServletsServlets
Servlets
 
Sockets in unix
Sockets in unixSockets in unix
Sockets in unix
 
Socket Programming In Python
Socket Programming In PythonSocket Programming In Python
Socket Programming In Python
 
Http
HttpHttp
Http
 

Andere mochten auch

Application Layer and Socket Programming
Application Layer and Socket ProgrammingApplication Layer and Socket Programming
Application Layer and Socket Programming
elliando dias
 
CIO_Defining a Career for the Future
CIO_Defining a Career for the FutureCIO_Defining a Career for the Future
CIO_Defining a Career for the Future
Michael Jenkins
 
renewable energies
renewable energiesrenewable energies
renewable energies
serzan2000
 
Tertawa Tersenyum Marah Hati
Tertawa   Tersenyum   Marah  HatiTertawa   Tersenyum   Marah  Hati
Tertawa Tersenyum Marah Hati
Cynthia D
 
Palacio de Cristal-Madrid
Palacio de Cristal-MadridPalacio de Cristal-Madrid
Palacio de Cristal-Madrid
Klagares16
 
Round 3 - S5PDH1 World Cup Stock Market
Round 3 - S5PDH1 World Cup Stock MarketRound 3 - S5PDH1 World Cup Stock Market
Round 3 - S5PDH1 World Cup Stock Market
Vas Ratusau
 
Maison de vacances Ploumoguer
Maison de vacances PloumoguerMaison de vacances Ploumoguer
Maison de vacances Ploumoguer
Erwan Person
 
Quality management introduction
Quality management introductionQuality management introduction
Quality management introduction
selinasimpson2801
 

Andere mochten auch (18)

socket programming
socket programming socket programming
socket programming
 
Application Layer and Socket Programming
Application Layer and Socket ProgrammingApplication Layer and Socket Programming
Application Layer and Socket Programming
 
Micro Programmed Control Unit
Micro Programmed Control UnitMicro Programmed Control Unit
Micro Programmed Control Unit
 
Application Layer
Application Layer Application Layer
Application Layer
 
CIO_Defining a Career for the Future
CIO_Defining a Career for the FutureCIO_Defining a Career for the Future
CIO_Defining a Career for the Future
 
Spectacu
SpectacuSpectacu
Spectacu
 
Hướng dẫn làm bt về chuỗi.doc
Hướng dẫn làm bt về chuỗi.docHướng dẫn làm bt về chuỗi.doc
Hướng dẫn làm bt về chuỗi.doc
 
renewable energies
renewable energiesrenewable energies
renewable energies
 
Tertawa Tersenyum Marah Hati
Tertawa   Tersenyum   Marah  HatiTertawa   Tersenyum   Marah  Hati
Tertawa Tersenyum Marah Hati
 
Palacio de Cristal-Madrid
Palacio de Cristal-MadridPalacio de Cristal-Madrid
Palacio de Cristal-Madrid
 
Round 3 - S5PDH1 World Cup Stock Market
Round 3 - S5PDH1 World Cup Stock MarketRound 3 - S5PDH1 World Cup Stock Market
Round 3 - S5PDH1 World Cup Stock Market
 
Maison de vacances Ploumoguer
Maison de vacances PloumoguerMaison de vacances Ploumoguer
Maison de vacances Ploumoguer
 
TDI | OOH Advertising +91 11 2619 2619
TDI | OOH Advertising +91 11 2619 2619TDI | OOH Advertising +91 11 2619 2619
TDI | OOH Advertising +91 11 2619 2619
 
Developing with Adobe AIR
Developing with Adobe AIRDeveloping with Adobe AIR
Developing with Adobe AIR
 
RAV Gazette Notice
RAV Gazette NoticeRAV Gazette Notice
RAV Gazette Notice
 
Ieee conference
Ieee conferenceIeee conference
Ieee conference
 
Quality management introduction
Quality management introductionQuality management introduction
Quality management introduction
 
Mievom Pres
Mievom PresMievom Pres
Mievom Pres
 

Ähnlich wie Socket Programming

Socket programming
Socket programmingSocket programming
Socket programming
harsh_bca06
 
Socket programming in C
Socket programming in CSocket programming in C
Socket programming in C
Deepak Swain
 

Ähnlich wie Socket Programming (20)

socket programming
 socket programming  socket programming
socket programming
 
Sockets
Sockets Sockets
Sockets
 
Os 2
Os 2Os 2
Os 2
 
Unit 8 Java
Unit 8 JavaUnit 8 Java
Unit 8 Java
 
Md13 networking
Md13 networkingMd13 networking
Md13 networking
 
Socket programming
Socket programmingSocket programming
Socket programming
 
Client server chat application
Client server chat applicationClient server chat application
Client server chat application
 
Lan chat system
Lan chat systemLan chat system
Lan chat system
 
EN-04 (1).pptx
EN-04 (1).pptxEN-04 (1).pptx
EN-04 (1).pptx
 
Java 1
Java 1Java 1
Java 1
 
Java_Socket_Programming (2).ppt
Java_Socket_Programming (2).pptJava_Socket_Programming (2).ppt
Java_Socket_Programming (2).ppt
 
java networking
 java networking java networking
java networking
 
Byte Ordering - Unit 2.pptx
Byte Ordering - Unit 2.pptxByte Ordering - Unit 2.pptx
Byte Ordering - Unit 2.pptx
 
Socket
SocketSocket
Socket
 
03 sockets
03 sockets03 sockets
03 sockets
 
Socket Programming
Socket ProgrammingSocket Programming
Socket Programming
 
Socket programming in C
Socket programming in CSocket programming in C
Socket programming in C
 
Java_Socket_Programming (2).ppt
Java_Socket_Programming (2).pptJava_Socket_Programming (2).ppt
Java_Socket_Programming (2).ppt
 
Network programming in Java
Network programming in JavaNetwork programming in Java
Network programming in Java
 
Network Prog.ppt
Network Prog.pptNetwork Prog.ppt
Network Prog.ppt
 

Mehr von elliando 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 ClojureScript
elliando dias
 
Nomenclatura e peças de container
Nomenclatura  e peças de containerNomenclatura  e peças de container
Nomenclatura e peças de container
elliando 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 Agility
elliando dias
 
Javascript Libraries
Javascript LibrariesJavascript Libraries
Javascript Libraries
elliando 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 Web
elliando dias
 
Introdução ao Arduino
Introdução ao ArduinoIntrodução ao Arduino
Introdução ao Arduino
elliando dias
 
Incanter Data Sorcery
Incanter Data SorceryIncanter Data Sorcery
Incanter Data Sorcery
elliando 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 Design
elliando 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 Facebook
elliando 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 Study
elliando 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

Kürzlich hochgeladen (20)

Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
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
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
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
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
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
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
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
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
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...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 

Socket Programming

  • 1. Socket Programming Srinidhi Varadarajan
  • 2. Client-server paradigm Client: application transport initiates contact with server network data link (“speaks first”) physical typically requests service request from server, for Web, client is implemented in browser; for e-mail, in mail reader reply Server: provides requested service application transport to client network data link physical e.g., Web server sends requested Web page, mail server delivers e-mail
  • 3. Application Layer Programming API: application programming interface defines interface between application and transport layer sockets: Internet API – two processes communicate by sending data into socket, reading data out of socket
  • 4. Socket Interface. What is it? Gives a file system like abstraction to the capabilities of the network. Each transport protocol offers a set of services. The socket API provides the abstraction to access these services The API defines function calls to create, close, read and write to/from a socket.
  • 5. Socket Abstraction The socket is the basic abstraction for network communication in the socket API – Defines an endpoint of communication for a process – Operating system maintains information about the socket and its connection – Application references the socket for sends, receives, etc. Network Process Process A B Ports (Sockets)
  • 6. What do you need for socket communication ? Basically 4 parameters – Source Identifier (IP address) – Source Port – Destination Identifier – Destination Port In the socket API, this information is communicated by binding the socket.
  • 7. Creating a socket int socket(int domain, int type, int protocol) Protocol Family: Usually PF_INET or UNSPEC PF_UNIX Communication semantics: SOCK_STREAM or SOCK_DGRAM The call returns a integer identifier called a handle
  • 8. Binding a socket int bind (int socket, struct sockaddr *address, int addr_len) This call is executed by: – Server in TCP and UDP It binds the socket to the specified address. The address parameter specifies the local component of the address, e.g. IP address and UDP/TCP port
  • 9. Socket Descriptors Operating system maintains a set of socket descriptors for each process – Note that socket descriptors are shared by threads Three data structures – Socket descriptor table – Socket data structure – Address data structure
  • 10. Socket Descriptors Socket Socket Data Descriptor Structure Table proto family: 0: PF_INET Address Data 1: service: Structure 2: SOCK_STREAM address family: . . local address: . AF_INET remote address: host IP: 128.173.88.85 . . . port: 80
  • 11. TCP Server Side: Listen int listen (int socket, int backlog) This server side call specifies the number of pending connections on the given socket. When the server is processing a connection, “backlog” number of connections may be pending in a queue.
  • 12. TCP Server Side: Passive Open int accept (int socket, struct sockaddr *address, int *addr_len) This call is executed by the server. The call does not return until a remote client has established a connection. When it completes, it returns a new socket handle corresponding to the just- established connection
  • 13. TCP Client Side: Active Open int connect (int socket, struct sockaddr *address, int *addr_len) This call is executed by the client. *address contains the remote address. The call attempts to connect the socket to a server. It does not return until a connection has been established. When the call completes, the socket “socket” is connected and ready for communication.
  • 14. Sockets: Summary Client: int socket(int domain, int type, int protocol) int connect (int socket, struct sockaddr *address, int addr_len) Server: int socket(int domain, int type, int protocol) int bind (int socket, struct sockaddr *address, int addr_len) int listen (int socket, int backlog) int accept (int socket, struct sockaddr *address, int *addr_len)
  • 15. Message Passing int send (int socket, char *message, int msg_len, int flags) (TCP) int sendto (int socket, void *msg, int len, int flags, struct sockaddr * to, int tolen ); (UDP) int write(int socket, void *msg, int len); /* TCP */ int recv (int socket, char *buffer, int buf_len, int flags) (TCP) int recvfrom(int socket, void *msg, int len, int flags, struct sockaddr *from, int *fromlen); (UDP) int read(int socket, void *msg, int len); (TCP)
  • 16. Summary of Basic Socket Calls CLIENT Connect SERVER (3-way handshake) connect() accept() new connection write() Data read() read() Data write() close() close()
  • 17. Network Byte Order Network byte order is most-significant byte first Byte ordering at a host may differ Utility functions – htons(): Host-to-network byte order for a short word (2 bytes) – htonl(): Host-to-network byte order for a long word (4 bytes) – ntohs(): Network-to-host byte order for a short word – ntohl(): Network-to-host byte order for a long word
  • 18. Some Other “Utility” Functions gethostname() -- get name of local host getpeername() -- get address of remote host getsockname() -- get local address of socket getXbyY() -- get protocol, host, or service number using known number, address, or port, respectively getsockopt() -- get current socket options setsockopt() -- set socket options ioctl() -- retrieve or set socket information
  • 19. Some Other “Utility” Functions inet_addr() -- convert “dotted” character string form of IP address to internal binary form inet_ntoa() -- convert internal binary form of IP address to “dotted” character string form
  • 20. Address Data Structures struct sockaddr { u_short sa_family; // type of address char sa_data[14]; // value of address } sockaddr is a generic address structure struct sockaddr_in { u_short sa_family; // type of address (AF_INET) u_short sa_port; // protocol port number struct in_addr sin_addr; // IP address char sin_zero[8]; // unused (set to zero) } sockaddr_in is specific instance for the Internet address family