SlideShare a Scribd company logo
Introduction
to Socket
Programming
Unit 2 Test Syllabus
• Application layer –I (Chapter 21)
• Socket Programming: Client-Server Model Of Interaction(21.1), The Client-Server Model
(21.2), A Trivial Example (21.3), : UDP Echo Server , Time And Date Service (21.4),
,Sequential And Concurrent Servers ,Server Complexity (21.5) , Broadcasting Requests
,Client-Server Alternatives And Extensions. (21.7),
• The Socket API (Chapter 22): Introduction (22.1),, Versions Of The Socket API (22.2), ,
The UNIX I/O Paradigm And Network I/O (22.3), ,Adding Network I/O to UNIX ,The
Socket Abstraction And Socket Operations, (22.4), Obtaining And Setting Socket Options
(22.12), ,How A Server Accepts TCP Connections (22.14), Servers That Handle Multiple
Services (22.15)
Inter process Communication
• IPC enables one application to control
another application, and for several
applications to share the same data without
interfering with one another.
Inter process Communication
• IPC is required in all multiprocessing systems, but it is not generally supported by
single-process operating systems.
• The various forms of IPC that are supported on a UNIX system are as follows :
• 1) Half duplex Pipes.
• 2) FIFO’s
• 3) Full duplex Pipes.
• 4) Named full duplex Pipes.
• 5) Message queues.
• 6) Shared memory.
• 7) Semaphores.
• 8) Sockets.
• 9) STREAMS.
• The first seven forms of IPC are usually restricted to IPC between processes on the same
host. The final two i.e. Sockets and STREAMS are the only two that are generally
supported for IPC between processes on different hosts.
•
Client-Server Model Of
Interaction
• The term server applies to any program that
offers a service that can be reached over a
network.
• A server accepts a request over the network,
performs its service, and returns the result to
the requester.
• For the simplest services, each request
arrives in a single IP datagram and the server
returns a response in another datagram.
• An executing program becomes a client
when it sends a request to a server and waits
for a response.
• Because the client-server model is a
convenient and natural extension of
interprocess communication on a single
machine, it is easy to build programs that use
the model to interact.
• Servers can perform simple or complex
tasks.
• For example, a time-of-day server merely
returns the current time whenever a client
sends the server a packet.
• A web server receives requests from a
browser to fetch a copy of a Web page; the
server obtains a copy of the file for the page
and returns it to the browser.
• servers are implemented as application programs.
• The advantage of implementing servers as application
programs is that they can execute on any computing system
that supports TCP/IP communication.
• Thus, the server for a particular service can execute on a
timesharing system along with other programs, or it can
execute on a personal computer.
• Multiple servers can offer the same service, and can
execute on the same machine or on multiple machines.
A Simple Example: UDP Echo
Server
• The simplest form of client-server interaction uses unreliable datagram delivery
to convey messages from a client to a server and back.
• Consider, for example, a UDP echo server. The mechanics are straightforward
as Figure shows.
• At the server site, a UDP echo server process begins by negotiating with its
operating system for permission to use the UDP port ID reserved for the echo
service, the UDP echo port. Once it has obtained permission, the echo server
process enters an infinite loop that has three steps: (1) wait for a datagram to
arrive at the echo port, (2) reverse the source and destination addresses
(including source and destination IP addresses as well as UDP port ids), and (3)
return the datagram to its original sender. At some other site, a program
becomes a UDP echo client when it allocates an unused UDP protocol port,
sends a UDP message to the UDP echo server, and awaits the reply. The client
expects to receive back exactly the same data as it sent.
• The UDP echo service illustrates two important points that are generally
true about client-server interaction. The first concerns the difference
between the lifetime of servers and clients:
• A server starts execution before interaction begins and (usually)
continues to accept requests and send responses without ever
terminating.
• A client is any program that makes a request and awaits a response; it
(usually) terminates after using a server a finite number of times.
• UDP echo as an example of the client-server model. In (a) the client
sends a request to the server at a known IP address and at a well-known
UDP port, and in (b) the server returns a response. Clients use any UDP
port that is available.
• The second point, which is more technical, concerns the use of reserved
and non-reserved port identifiers: response sent to client's port
• A server waits for requests at a well-known port that has been reserved
for the service it offers. A client allocates an arbitrary, unused
nonreserved port for its communication.
• In a client-server interaction, only one of the two ports needs to be
reserved. Assigning a unique port identifier to each service makes it
easy to build both clients and servers.
Time And Date Service
The Complexity of Servers
sockets SMTP Bmsce ppt information science and engineering
The Socket Interface
The interface between application programs
and TCP/IP protocols.
The UNIX I/O Paradigm And Network I/O
•UNIX was originally designed as a timesharing system for
single processor computers.
•It is a process-oriented operating system in which each
application program executes as a user level process.
•An application program interacts with the operating system by
making system calls.
• Before a user process can perform I/O operations,
it calls open to specify the file or device to be used
and obtains permission.
• The call to open returns a small integer file
descriptor to that the process uses when performing
I/O operations on the opened file or device.
• Both read and write take three arguments that
specify the file descriptor to use, the address of a
buffer, and the number of bytes to transfer.
• After all transfer operations are complete, the user
process calls close to inform the operating system
that it has finished using the object
Adding Network I/O to UNIX
• An early implementation of TCP/IP under
UNIX also used the open-read-write-close
paradigm with a special file name, /dev/tcp.
• Interaction between user processes and
network protocols must be more complex
than interactions between user processes and
conventional I/O facilities
Socket
• What is socket?
• A socket is one endpoint of a two-way communication link between two
programs running on the network. The application creates a socket.
Socket is an interface between application layer and transport layer.
• It is an interface (a “door”) into which an application process can both
send and receive message to/from another application process
(remote/local application process). Socket is also referred as the
application programmer’s interface (API) between the application and
the network.
• Need of Socket
• When we desire a communication between two applications possibly running on
different machines, we need sockets. Requirement of socket is to build any
Network Application i.e., Web browsers, FTP etc…
sockets SMTP Bmsce ppt information science and engineering
How Socket Works
• There are two different programs running on two different
machines in network.
• Client program wants to communicate with server program.
• Client select any free port from client machine and send
data to server process.
• Server select port which is bind with particular server
process. That port is called agreed or specific port.
• After that logical connection is created between client and
server. Server received client process at agreed/specific
port. Then communication is started between server and
client.
• Socket is combination of IP address and Port number. IP address is used
for host-to-host communication in network. IP address is assigned by
network layer. Port number is used for process-to-process
communication in network. Port number is assigned by transport layers
protocol.
• Let’s take one example, there is one Server host and Client host in above
diagram. There are two different servers are configured on server host. Client
send a request message to server. Request message is received from port
number 80. At server-side Web server is bind with port number 80. So, Sever
OS forward that request message to Web server. Process is identify based on
port address. Port address is already assigned in unique socket address.
• Types of Sockets
• There are two types of sockets: Stream Socket and Datagram Socket.
• Stream Socket
• Stream socket is also called connection- oriented socket. It provides reliable, connected
networking service. Error free; no out- of- order packets (uses TCP). Applications of
Stream Sockets are telnet/SSH, http, https and many more.
• Datagram Socket
• Datagram socket is also known as Connectionless socket. It provides unreliable, best-
effort networking service Packets may be lost; may arrive out of order (uses UDP).
Application of Datagram Sockets are streaming audio/ video (real player) and many more.
• Raw Socket, Sequenced packet Socket etc.
Blocking Mode
• A socket is in blocking mode when an I/O
call waits for an event to complete. If the
blocking mode is set for a socket, the calling
program is suspended until the expected
event completes.
• Blocking
• The default mode of socket calls is blocking. A blocking call does not
return to your program until the event you requested has been
completed. For example, if you issue a blocking recvfrom() call, the call
does not return to your program until data is available from the other
socket application. A blocking accept() call does not return to your
program until a client connects to your socket program.
• Nonblocking
• Nonblocking calls return to your program immediately to reveal
whether the requested service was completed.
Transport Service Primitives
• The primitives for a simple transport service.
• Getting back to our client-server example, the client’s CONNECT call causes a
CONNECTION REQUEST segment to be sent to the server.
• When it arrives, the transport entity checks to see that the server is blocked on a
LISTEN (i.e., is interested in handling requests).
• If so, it then unblocks the server and sends a CONNECTION ACCEPTED
segment back to the client.
• When this segment arrives, the client is unblocked and the connection is
established.
• Data can now be exchanged using the SEND and RECEIVE primitives. In the
simplest form, either party can do a (blocking) RECEIVE to wait for the other
party to do a SEND.
• When the segment arrives, the receiver is unblocked. It can then process the
segment and send a reply. As long as both sides can keep track of whose turn it
is to send, this scheme works fine.
• A state diagram for connection establishment and release for these
simple primitives is given in Fig. Each transition is triggered by some
event, either a primitive executed by the local transport user or an
incoming packet.
• For simplicity, we assume here that each segment is separately
acknowledged. We also assume that a symmetric disconnection model
is used, with the client going first.
sockets SMTP Bmsce ppt information science and engineering
sockets SMTP Bmsce ppt information science and engineering
Socket Families
There are several significant socket
domain families:
⇨Internet Domain Sockets (AF_INET)
-implemented via IP addresses and
port numbers
⇨Unix Domain Sockets (AF_UNIX)
-implemented via filenames (think
“named pipe”)
⇨Novell IPX (AF_IPX)
⇨AppleTalk DDS (AF_APPLETALK)
Type of Socket
• Stream (SOCK_STREAM) Uses TCP protocol.
Connection-oriented service
• Datagram (SOCK_DGRAM) Uses UDP protocol.
Connectionless service
• Raw (SOCK_RAW) Used for testing
sockets SMTP Bmsce ppt information science and engineering
sockets SMTP Bmsce ppt information science and engineering
sockets SMTP Bmsce ppt information science and engineering
• The bind() system call associates a socket
with a particular name or address. In other
words, this call specifies the port a server
process will listen to. The function
prototype is as follows:
• int bind(int sockfd, struct sockaddr
*my_addr, socklen_t addrlen);
• where sockfd is the socket file descriptor returned from a
previous socket() call,
• my_addr is a pointer to a structure containing the address to
bind to, and addrlen is the size of the structure.
• The key to using this call is understanding how to fill in
the fields of the sockaddr structure. This structure (defined
in netinet/in.h) contains fields for the address family
(sin_family), the IP address of the host (sin_addr.s_addr),
the port number (sin_port), and some padding. Here is a
typical bind() call:
• bind (sockfd, (struct sockaddr *) &server, sizeof(server));
• This call binds the socket sockfd to the address contained in
the structure named server.
• Within the structure server, the field family has been set to
AF_INET, specifying the Internet address domain.
• The port number has been set (using the htons() function
for portability) to any currently unused number on that
system. Finally, since this is a server, the IP address has
been set to INADDR_ANY, specifying that connections
will be accepted from any other host.
sockets SMTP Bmsce ppt information science and engineering
Listen()
• The listen() system call establishes the size of the incoming request queue.
Although the listen() call is not strictly necessary, it is commonly used. The
function prototype is as follows:
• int listen(int s, int backlog);
• where s is the socket and backlog is the size of the queue (i.e. the maximum
queued connection requests). Here is a typical listen() call:
• listen (sockfd, MAXCONNECT);
• This call specifies that the socket sockfd will queue up to MAXCONNECT
requests.
sockets SMTP Bmsce ppt information science and engineering
TCP Client/Server
sockets SMTP Bmsce ppt information science and engineering
TCP Server
• Sequence of calls
sock_init() Create the socket
bind() Register port with the system
listen() Establish client connection
accept() Accept client connection
read/write read/write data
close() shutdown
TCP Client
• Sequence of calls
sock_init () Create socket
connect() Set up connection
write/read write/read data
close() Shutdown
Server Side Socket Details
Client Side Socket Details
UDP Clients and Servers
• Connectionless clients and servers create a socket using SOCK_DGRAM
instead of SOCK_STREAM
• Connectionless servers do not call listen() or accept(), and usually do not call
connect()
• Since connectionless communications lack a sustained connection, several
methods are available that allow you to specify a destination address with
every call:
– sendto(sock, buffer, buflen, flags, to_addr, tolen);
– recvfrom(sock, buffer, buflen, flags, from_addr, fromlen);
UDP Server
• Sequence of calls
sock_init() Create socket
bind() Register port with the system
recfrom/sendto Receive/send data
close() Shutdown
UDP Client
• Sequence of calls
socket_init() Create socket
sendto/recfrom send/receive data
close() Shutdown
The Socket Abstraction
• The basis for network I/0 in the socket API centers on an
abstraction known as the socket.
• The chief difference between file descriptors and socket
descriptors is that the operating system binds a file
descriptor to a specific file or device when the application
calls open, but it can create sockets without binding them to
specific destination addresses.
• The application can choose to supply a destination address
each time it uses the socket (e.g., when sending datagrams),
or it can choose to bind the destination address to the socket
and avoid specifying the destination repeatedly
Socket types define the communication properties visible to a user.
The Internet domain sockets provide access to the TCP/IP
transport protocols. The Internet domain is identified by the value
AF_INET. Sockets exchange data only with sockets in the same
domain. Three types of sockets are supported:
1.Stream sockets allow processes to communicate using TCP. A stream socket provides
bidirectional, reliable, sequenced, and unduplicated flow of data with no record
boundaries. Once the connection has been established, data can be read from and written
to these sockets as a byte stream. The socket type is SOCK_STREAM.
2. Datagram sockets allow processes to use UDP to communicate. A datagram socket
supports bidirectional flow of messages. A process on a datagram socket may receive
messages in a different order from the sending sequence and may receive duplicate
messages. Record boundaries in the data are preserved. The socket type is
SOCK_DGRAM.
3. Raw sockets provide access to ICMP. These sockets are normally datagram oriented,
although their exact characteristics are dependent on the interface provided by the
protocol. Raw sockets are not for most applications. They are provided to support
developing new communication protocols or for access to more esoteric facilities of an
existing protocol. Only superuser processes may use raw sockets
Declaration for socket function
sockets SMTP Bmsce ppt information science and engineering
Socket types
Binding Local Names
A socket is created with no name. A remote process has no way to refer to
a
socket until an address is bound to it. Communicating processes are
connected through addresses. In the Internet domain, a connection is
composed of local and remote addresses, and local and remote ports. In the
UNIX domain, a connection is composed of (usually) one or two path
names. In most domains, connections must be unique.
sockets SMTP Bmsce ppt information science and engineering
Declaration for bind function
sockfd is the socket file descriptor returned by socket().
localaddr is a pointer to a struct sockaddr that contains information
about your address, namely, port and IP address.
localaddrlen can be set to sizeof(struct sockaddr).
By setting localaddr.sin_port to zero, you are telling bind() to
choose the port for you.
IANA Port Numbers Ranges
The Internet Assigned Numbers Authority(IANA)
http://www.iana.org/assignments/port-numbers
Declaration for listen function
sockfd is the usual socket file descriptor from the socket() system call.
backlog is the number of connections allowed on the incoming
queue.
Declaration for connect function
sockfd is the socket file descriptor, as returned by the socket() call. But can
be used to communicate with server after successfully called connect().
serveraddr is a struct sockaddr containing the destination port and IP
address.
serveraddrlen can be set to sizeof(struct sockaddr).
Declaration for accept function
sockfd is the listen()ing socket descriptor. Easy enough.
clientaddr will usually be a pointer to a local struct sockaddr_in. This is
where the information about the incoming connection will go (and with it
you can determine which host is calling you from which port).
clientaddrlen is a local integer variable that should be set to sizeof(struct
sockaddr_in) before its address is passed to accept().
Declaration for close function
Declaration for write function
Used in connection-oriented (TCP) program.
sockfd is the socket descriptor you want to send data to (whether it's the
one returned by socket() or the one you got with accept().) buf is a
pointer to the data you want to send, and buflen is the length of that data
in bytes.
If the value returned by write() doesn't match the value in buflen, it's up
to you to send the rest of the string.
Ssize_t send(int sockfd, const void *buf, int buflen, int flags);
Just set flags to 0. Set flag=MSG_OOB to send out-of-band data.
Declaration for read function
Used in connection-oriented (TCP) program.
sockfd is the socket descriptor to read from, buf is the buffer to read the information
into, buflen is the maximum length of the buffer, flags can again be set to 0.
Set flag=MSG_OOB to read out-of-band data.
A similar system call
ssize_t recv(int sockfd, void *buf, int len, unsigned int flags);
Declaration for sendto function
Used in connection-less (UDP) program.
toaddr is a pointer to a struct sockaddr (or struct sockaddr_in which contains
the destination IP address and port).
toaddrlen can simply be set to sizeof(struct sockaddr).
Declaration for recvfrom function
Used in connection-less (UDP) program.
fromaddr is a pointer to a struct sockaddr (or struct sockaddr_in which
contains the IP address and port of the sender).
fromaddrlen can simply be set to sizeof(struct sockaddr).
CONNECTIONLESS
ITERATIVE
SERVER &
UDP CLIENT-SERVER
PROGRAMS
Socket interface
for connectionless
iterative server
Connectionless
Service (UDP)
Server
Client
1. Create transport
endpoint: socket()
2. Assign transport
endpoint an
address: bind()
3. Wait for a packet
to arrive: recvfrom()
4. Formulate reply (if any)
and send: sendto()
5. Release transport
endpoint: close()
1. Create transport
endpoint: socket()
2. Assign transport
endpoint an
address (optional):
bind()
3. Determine address
of server
4. Formulate message
and send: sendto()
6. Release transport
endpoint: close()
5. Wait for packet
to arrive: recvfrom()
CONNECTION-ORIENTED
CONCURRENT SERVER
Socket interface
for connection-oriented
concurrent server
Part I
Part II
Part I
Client
and
Server

More Related Content

Similar to sockets SMTP Bmsce ppt information science and engineering (20)

PPT
Sockets in unix
swtjerin4u
 
PPTX
Byte Ordering - Unit 2.pptx
RockyBhai46825
 
PPTX
Linux Inter Process Communication
Abhishek Sagar
 
PDF
How a network connection is created A network connection is initi.pdf
arccreation001
 
PDF
Socket Programming
elliando dias
 
PDF
Socket programming using java
UC San Diego
 
PPT
Design an Implementation of A Messaging and Resource Sharing Software
nilabarai
 
PPTX
Inter process communication by Dr.C.R.Dhivyaa, Assistant Professor,Kongu Engi...
Dhivyaa C.R
 
PDF
Gu3112991305
IJERA Editor
 
DOC
socket programming
prashantzagade
 
DOC
socket programming
prashantzagade
 
PPTX
Java socket programming
Mohammed Abdalla Youssif
 
PDF
CODE FOR echo_client.c A simple echo client using TCP #inc.pdf
secunderbadtirumalgi
 
PPT
Network programming-Network for engineering
insdcn
 
PPT
Network Prog.ppt
EloOgardo
 
PPT
Npc08
vamsitricks
 
PPTX
Distributed Computing - API for Internet Protocols
nirmalanr2
 
DOCX
Application programming interface sockets
Kamran Ashraf
 
PPT
Socket programming in C
Deepak Swain
 
PPT
LECTURE-17(Socket Programming) Detailed.
qamarmajeed0000
 
Sockets in unix
swtjerin4u
 
Byte Ordering - Unit 2.pptx
RockyBhai46825
 
Linux Inter Process Communication
Abhishek Sagar
 
How a network connection is created A network connection is initi.pdf
arccreation001
 
Socket Programming
elliando dias
 
Socket programming using java
UC San Diego
 
Design an Implementation of A Messaging and Resource Sharing Software
nilabarai
 
Inter process communication by Dr.C.R.Dhivyaa, Assistant Professor,Kongu Engi...
Dhivyaa C.R
 
Gu3112991305
IJERA Editor
 
socket programming
prashantzagade
 
socket programming
prashantzagade
 
Java socket programming
Mohammed Abdalla Youssif
 
CODE FOR echo_client.c A simple echo client using TCP #inc.pdf
secunderbadtirumalgi
 
Network programming-Network for engineering
insdcn
 
Network Prog.ppt
EloOgardo
 
Distributed Computing - API for Internet Protocols
nirmalanr2
 
Application programming interface sockets
Kamran Ashraf
 
Socket programming in C
Deepak Swain
 
LECTURE-17(Socket Programming) Detailed.
qamarmajeed0000
 

Recently uploaded (20)

PDF
2010_Book_EnvironmentalBioengineering (1).pdf
EmilianoRodriguezTll
 
PDF
Natural_Language_processing_Unit_I_notes.pdf
sanguleumeshit
 
PPTX
Inventory management chapter in automation and robotics.
atisht0104
 
PDF
All chapters of Strength of materials.ppt
girmabiniyam1234
 
PDF
settlement FOR FOUNDATION ENGINEERS.pdf
Endalkazene
 
PDF
EVS+PRESENTATIONS EVS+PRESENTATIONS like
saiyedaqib429
 
PPTX
quantum computing transition from classical mechanics.pptx
gvlbcy
 
PPTX
Chapter_Seven_Construction_Reliability_Elective_III_Msc CM
SubashKumarBhattarai
 
PDF
Air -Powered Car PPT by ER. SHRESTH SUDHIR KOKNE.pdf
SHRESTHKOKNE
 
PDF
Advanced LangChain & RAG: Building a Financial AI Assistant with Real-Time Data
Soufiane Sejjari
 
PPTX
MT Chapter 1.pptx- Magnetic particle testing
ABCAnyBodyCanRelax
 
PPTX
Online Cab Booking and Management System.pptx
diptipaneri80
 
PPTX
Information Retrieval and Extraction - Module 7
premSankar19
 
PDF
Packaging Tips for Stainless Steel Tubes and Pipes
heavymetalsandtubes
 
PPTX
filteration _ pre.pptx 11111110001.pptx
awasthivaibhav825
 
PPTX
ENSA_Module_7.pptx_wide_area_network_concepts
RanaMukherjee24
 
PDF
Zero carbon Building Design Guidelines V4
BassemOsman1
 
PPTX
MULTI LEVEL DATA TRACKING USING COOJA.pptx
dollysharma12ab
 
PDF
STUDY OF NOVEL CHANNEL MATERIALS USING III-V COMPOUNDS WITH VARIOUS GATE DIEL...
ijoejnl
 
PPTX
FUNDAMENTALS OF ELECTRIC VEHICLES UNIT-1
MikkiliSuresh
 
2010_Book_EnvironmentalBioengineering (1).pdf
EmilianoRodriguezTll
 
Natural_Language_processing_Unit_I_notes.pdf
sanguleumeshit
 
Inventory management chapter in automation and robotics.
atisht0104
 
All chapters of Strength of materials.ppt
girmabiniyam1234
 
settlement FOR FOUNDATION ENGINEERS.pdf
Endalkazene
 
EVS+PRESENTATIONS EVS+PRESENTATIONS like
saiyedaqib429
 
quantum computing transition from classical mechanics.pptx
gvlbcy
 
Chapter_Seven_Construction_Reliability_Elective_III_Msc CM
SubashKumarBhattarai
 
Air -Powered Car PPT by ER. SHRESTH SUDHIR KOKNE.pdf
SHRESTHKOKNE
 
Advanced LangChain & RAG: Building a Financial AI Assistant with Real-Time Data
Soufiane Sejjari
 
MT Chapter 1.pptx- Magnetic particle testing
ABCAnyBodyCanRelax
 
Online Cab Booking and Management System.pptx
diptipaneri80
 
Information Retrieval and Extraction - Module 7
premSankar19
 
Packaging Tips for Stainless Steel Tubes and Pipes
heavymetalsandtubes
 
filteration _ pre.pptx 11111110001.pptx
awasthivaibhav825
 
ENSA_Module_7.pptx_wide_area_network_concepts
RanaMukherjee24
 
Zero carbon Building Design Guidelines V4
BassemOsman1
 
MULTI LEVEL DATA TRACKING USING COOJA.pptx
dollysharma12ab
 
STUDY OF NOVEL CHANNEL MATERIALS USING III-V COMPOUNDS WITH VARIOUS GATE DIEL...
ijoejnl
 
FUNDAMENTALS OF ELECTRIC VEHICLES UNIT-1
MikkiliSuresh
 
Ad

sockets SMTP Bmsce ppt information science and engineering

  • 2. Unit 2 Test Syllabus • Application layer –I (Chapter 21) • Socket Programming: Client-Server Model Of Interaction(21.1), The Client-Server Model (21.2), A Trivial Example (21.3), : UDP Echo Server , Time And Date Service (21.4), ,Sequential And Concurrent Servers ,Server Complexity (21.5) , Broadcasting Requests ,Client-Server Alternatives And Extensions. (21.7), • The Socket API (Chapter 22): Introduction (22.1),, Versions Of The Socket API (22.2), , The UNIX I/O Paradigm And Network I/O (22.3), ,Adding Network I/O to UNIX ,The Socket Abstraction And Socket Operations, (22.4), Obtaining And Setting Socket Options (22.12), ,How A Server Accepts TCP Connections (22.14), Servers That Handle Multiple Services (22.15)
  • 3. Inter process Communication • IPC enables one application to control another application, and for several applications to share the same data without interfering with one another.
  • 4. Inter process Communication • IPC is required in all multiprocessing systems, but it is not generally supported by single-process operating systems. • The various forms of IPC that are supported on a UNIX system are as follows : • 1) Half duplex Pipes. • 2) FIFO’s • 3) Full duplex Pipes. • 4) Named full duplex Pipes. • 5) Message queues. • 6) Shared memory. • 7) Semaphores. • 8) Sockets. • 9) STREAMS. • The first seven forms of IPC are usually restricted to IPC between processes on the same host. The final two i.e. Sockets and STREAMS are the only two that are generally supported for IPC between processes on different hosts. •
  • 5. Client-Server Model Of Interaction • The term server applies to any program that offers a service that can be reached over a network. • A server accepts a request over the network, performs its service, and returns the result to the requester. • For the simplest services, each request arrives in a single IP datagram and the server returns a response in another datagram.
  • 6. • An executing program becomes a client when it sends a request to a server and waits for a response. • Because the client-server model is a convenient and natural extension of interprocess communication on a single machine, it is easy to build programs that use the model to interact.
  • 7. • Servers can perform simple or complex tasks. • For example, a time-of-day server merely returns the current time whenever a client sends the server a packet. • A web server receives requests from a browser to fetch a copy of a Web page; the server obtains a copy of the file for the page and returns it to the browser.
  • 8. • servers are implemented as application programs. • The advantage of implementing servers as application programs is that they can execute on any computing system that supports TCP/IP communication. • Thus, the server for a particular service can execute on a timesharing system along with other programs, or it can execute on a personal computer. • Multiple servers can offer the same service, and can execute on the same machine or on multiple machines.
  • 9. A Simple Example: UDP Echo Server • The simplest form of client-server interaction uses unreliable datagram delivery to convey messages from a client to a server and back. • Consider, for example, a UDP echo server. The mechanics are straightforward as Figure shows. • At the server site, a UDP echo server process begins by negotiating with its operating system for permission to use the UDP port ID reserved for the echo service, the UDP echo port. Once it has obtained permission, the echo server process enters an infinite loop that has three steps: (1) wait for a datagram to arrive at the echo port, (2) reverse the source and destination addresses (including source and destination IP addresses as well as UDP port ids), and (3) return the datagram to its original sender. At some other site, a program becomes a UDP echo client when it allocates an unused UDP protocol port, sends a UDP message to the UDP echo server, and awaits the reply. The client expects to receive back exactly the same data as it sent.
  • 10. • The UDP echo service illustrates two important points that are generally true about client-server interaction. The first concerns the difference between the lifetime of servers and clients: • A server starts execution before interaction begins and (usually) continues to accept requests and send responses without ever terminating. • A client is any program that makes a request and awaits a response; it (usually) terminates after using a server a finite number of times.
  • 11. • UDP echo as an example of the client-server model. In (a) the client sends a request to the server at a known IP address and at a well-known UDP port, and in (b) the server returns a response. Clients use any UDP port that is available.
  • 12. • The second point, which is more technical, concerns the use of reserved and non-reserved port identifiers: response sent to client's port • A server waits for requests at a well-known port that has been reserved for the service it offers. A client allocates an arbitrary, unused nonreserved port for its communication. • In a client-server interaction, only one of the two ports needs to be reserved. Assigning a unique port identifier to each service makes it easy to build both clients and servers.
  • 13. Time And Date Service
  • 14. The Complexity of Servers
  • 16. The Socket Interface The interface between application programs and TCP/IP protocols. The UNIX I/O Paradigm And Network I/O •UNIX was originally designed as a timesharing system for single processor computers. •It is a process-oriented operating system in which each application program executes as a user level process. •An application program interacts with the operating system by making system calls.
  • 17. • Before a user process can perform I/O operations, it calls open to specify the file or device to be used and obtains permission. • The call to open returns a small integer file descriptor to that the process uses when performing I/O operations on the opened file or device. • Both read and write take three arguments that specify the file descriptor to use, the address of a buffer, and the number of bytes to transfer. • After all transfer operations are complete, the user process calls close to inform the operating system that it has finished using the object
  • 18. Adding Network I/O to UNIX • An early implementation of TCP/IP under UNIX also used the open-read-write-close paradigm with a special file name, /dev/tcp. • Interaction between user processes and network protocols must be more complex than interactions between user processes and conventional I/O facilities
  • 19. Socket • What is socket? • A socket is one endpoint of a two-way communication link between two programs running on the network. The application creates a socket. Socket is an interface between application layer and transport layer. • It is an interface (a “door”) into which an application process can both send and receive message to/from another application process (remote/local application process). Socket is also referred as the application programmer’s interface (API) between the application and the network. • Need of Socket • When we desire a communication between two applications possibly running on different machines, we need sockets. Requirement of socket is to build any Network Application i.e., Web browsers, FTP etc…
  • 21. How Socket Works • There are two different programs running on two different machines in network. • Client program wants to communicate with server program. • Client select any free port from client machine and send data to server process. • Server select port which is bind with particular server process. That port is called agreed or specific port. • After that logical connection is created between client and server. Server received client process at agreed/specific port. Then communication is started between server and client.
  • 22. • Socket is combination of IP address and Port number. IP address is used for host-to-host communication in network. IP address is assigned by network layer. Port number is used for process-to-process communication in network. Port number is assigned by transport layers protocol.
  • 23. • Let’s take one example, there is one Server host and Client host in above diagram. There are two different servers are configured on server host. Client send a request message to server. Request message is received from port number 80. At server-side Web server is bind with port number 80. So, Sever OS forward that request message to Web server. Process is identify based on port address. Port address is already assigned in unique socket address.
  • 24. • Types of Sockets • There are two types of sockets: Stream Socket and Datagram Socket. • Stream Socket • Stream socket is also called connection- oriented socket. It provides reliable, connected networking service. Error free; no out- of- order packets (uses TCP). Applications of Stream Sockets are telnet/SSH, http, https and many more. • Datagram Socket • Datagram socket is also known as Connectionless socket. It provides unreliable, best- effort networking service Packets may be lost; may arrive out of order (uses UDP). Application of Datagram Sockets are streaming audio/ video (real player) and many more. • Raw Socket, Sequenced packet Socket etc.
  • 25. Blocking Mode • A socket is in blocking mode when an I/O call waits for an event to complete. If the blocking mode is set for a socket, the calling program is suspended until the expected event completes.
  • 26. • Blocking • The default mode of socket calls is blocking. A blocking call does not return to your program until the event you requested has been completed. For example, if you issue a blocking recvfrom() call, the call does not return to your program until data is available from the other socket application. A blocking accept() call does not return to your program until a client connects to your socket program. • Nonblocking • Nonblocking calls return to your program immediately to reveal whether the requested service was completed.
  • 27. Transport Service Primitives • The primitives for a simple transport service.
  • 28. • Getting back to our client-server example, the client’s CONNECT call causes a CONNECTION REQUEST segment to be sent to the server. • When it arrives, the transport entity checks to see that the server is blocked on a LISTEN (i.e., is interested in handling requests). • If so, it then unblocks the server and sends a CONNECTION ACCEPTED segment back to the client. • When this segment arrives, the client is unblocked and the connection is established. • Data can now be exchanged using the SEND and RECEIVE primitives. In the simplest form, either party can do a (blocking) RECEIVE to wait for the other party to do a SEND. • When the segment arrives, the receiver is unblocked. It can then process the segment and send a reply. As long as both sides can keep track of whose turn it is to send, this scheme works fine.
  • 29. • A state diagram for connection establishment and release for these simple primitives is given in Fig. Each transition is triggered by some event, either a primitive executed by the local transport user or an incoming packet. • For simplicity, we assume here that each segment is separately acknowledged. We also assume that a symmetric disconnection model is used, with the client going first.
  • 32. Socket Families There are several significant socket domain families: ⇨Internet Domain Sockets (AF_INET) -implemented via IP addresses and port numbers ⇨Unix Domain Sockets (AF_UNIX) -implemented via filenames (think “named pipe”) ⇨Novell IPX (AF_IPX) ⇨AppleTalk DDS (AF_APPLETALK)
  • 33. Type of Socket • Stream (SOCK_STREAM) Uses TCP protocol. Connection-oriented service • Datagram (SOCK_DGRAM) Uses UDP protocol. Connectionless service • Raw (SOCK_RAW) Used for testing
  • 37. • The bind() system call associates a socket with a particular name or address. In other words, this call specifies the port a server process will listen to. The function prototype is as follows: • int bind(int sockfd, struct sockaddr *my_addr, socklen_t addrlen);
  • 38. • where sockfd is the socket file descriptor returned from a previous socket() call, • my_addr is a pointer to a structure containing the address to bind to, and addrlen is the size of the structure. • The key to using this call is understanding how to fill in the fields of the sockaddr structure. This structure (defined in netinet/in.h) contains fields for the address family (sin_family), the IP address of the host (sin_addr.s_addr), the port number (sin_port), and some padding. Here is a typical bind() call: • bind (sockfd, (struct sockaddr *) &server, sizeof(server));
  • 39. • This call binds the socket sockfd to the address contained in the structure named server. • Within the structure server, the field family has been set to AF_INET, specifying the Internet address domain. • The port number has been set (using the htons() function for portability) to any currently unused number on that system. Finally, since this is a server, the IP address has been set to INADDR_ANY, specifying that connections will be accepted from any other host.
  • 41. Listen() • The listen() system call establishes the size of the incoming request queue. Although the listen() call is not strictly necessary, it is commonly used. The function prototype is as follows: • int listen(int s, int backlog); • where s is the socket and backlog is the size of the queue (i.e. the maximum queued connection requests). Here is a typical listen() call: • listen (sockfd, MAXCONNECT); • This call specifies that the socket sockfd will queue up to MAXCONNECT requests.
  • 45. TCP Server • Sequence of calls sock_init() Create the socket bind() Register port with the system listen() Establish client connection accept() Accept client connection read/write read/write data close() shutdown
  • 46. TCP Client • Sequence of calls sock_init () Create socket connect() Set up connection write/read write/read data close() Shutdown
  • 49. UDP Clients and Servers • Connectionless clients and servers create a socket using SOCK_DGRAM instead of SOCK_STREAM • Connectionless servers do not call listen() or accept(), and usually do not call connect() • Since connectionless communications lack a sustained connection, several methods are available that allow you to specify a destination address with every call: – sendto(sock, buffer, buflen, flags, to_addr, tolen); – recvfrom(sock, buffer, buflen, flags, from_addr, fromlen);
  • 50. UDP Server • Sequence of calls sock_init() Create socket bind() Register port with the system recfrom/sendto Receive/send data close() Shutdown
  • 51. UDP Client • Sequence of calls socket_init() Create socket sendto/recfrom send/receive data close() Shutdown
  • 52. The Socket Abstraction • The basis for network I/0 in the socket API centers on an abstraction known as the socket. • The chief difference between file descriptors and socket descriptors is that the operating system binds a file descriptor to a specific file or device when the application calls open, but it can create sockets without binding them to specific destination addresses. • The application can choose to supply a destination address each time it uses the socket (e.g., when sending datagrams), or it can choose to bind the destination address to the socket and avoid specifying the destination repeatedly
  • 53. Socket types define the communication properties visible to a user. The Internet domain sockets provide access to the TCP/IP transport protocols. The Internet domain is identified by the value AF_INET. Sockets exchange data only with sockets in the same domain. Three types of sockets are supported: 1.Stream sockets allow processes to communicate using TCP. A stream socket provides bidirectional, reliable, sequenced, and unduplicated flow of data with no record boundaries. Once the connection has been established, data can be read from and written to these sockets as a byte stream. The socket type is SOCK_STREAM. 2. Datagram sockets allow processes to use UDP to communicate. A datagram socket supports bidirectional flow of messages. A process on a datagram socket may receive messages in a different order from the sending sequence and may receive duplicate messages. Record boundaries in the data are preserved. The socket type is SOCK_DGRAM. 3. Raw sockets provide access to ICMP. These sockets are normally datagram oriented, although their exact characteristics are dependent on the interface provided by the protocol. Raw sockets are not for most applications. They are provided to support developing new communication protocols or for access to more esoteric facilities of an existing protocol. Only superuser processes may use raw sockets
  • 57. Binding Local Names A socket is created with no name. A remote process has no way to refer to a socket until an address is bound to it. Communicating processes are connected through addresses. In the Internet domain, a connection is composed of local and remote addresses, and local and remote ports. In the UNIX domain, a connection is composed of (usually) one or two path names. In most domains, connections must be unique.
  • 59. Declaration for bind function sockfd is the socket file descriptor returned by socket(). localaddr is a pointer to a struct sockaddr that contains information about your address, namely, port and IP address. localaddrlen can be set to sizeof(struct sockaddr). By setting localaddr.sin_port to zero, you are telling bind() to choose the port for you.
  • 60. IANA Port Numbers Ranges The Internet Assigned Numbers Authority(IANA) http://www.iana.org/assignments/port-numbers
  • 61. Declaration for listen function sockfd is the usual socket file descriptor from the socket() system call. backlog is the number of connections allowed on the incoming queue.
  • 62. Declaration for connect function sockfd is the socket file descriptor, as returned by the socket() call. But can be used to communicate with server after successfully called connect(). serveraddr is a struct sockaddr containing the destination port and IP address. serveraddrlen can be set to sizeof(struct sockaddr).
  • 63. Declaration for accept function sockfd is the listen()ing socket descriptor. Easy enough. clientaddr will usually be a pointer to a local struct sockaddr_in. This is where the information about the incoming connection will go (and with it you can determine which host is calling you from which port). clientaddrlen is a local integer variable that should be set to sizeof(struct sockaddr_in) before its address is passed to accept().
  • 65. Declaration for write function Used in connection-oriented (TCP) program. sockfd is the socket descriptor you want to send data to (whether it's the one returned by socket() or the one you got with accept().) buf is a pointer to the data you want to send, and buflen is the length of that data in bytes. If the value returned by write() doesn't match the value in buflen, it's up to you to send the rest of the string. Ssize_t send(int sockfd, const void *buf, int buflen, int flags); Just set flags to 0. Set flag=MSG_OOB to send out-of-band data.
  • 66. Declaration for read function Used in connection-oriented (TCP) program. sockfd is the socket descriptor to read from, buf is the buffer to read the information into, buflen is the maximum length of the buffer, flags can again be set to 0. Set flag=MSG_OOB to read out-of-band data. A similar system call ssize_t recv(int sockfd, void *buf, int len, unsigned int flags);
  • 67. Declaration for sendto function Used in connection-less (UDP) program. toaddr is a pointer to a struct sockaddr (or struct sockaddr_in which contains the destination IP address and port). toaddrlen can simply be set to sizeof(struct sockaddr).
  • 68. Declaration for recvfrom function Used in connection-less (UDP) program. fromaddr is a pointer to a struct sockaddr (or struct sockaddr_in which contains the IP address and port of the sender). fromaddrlen can simply be set to sizeof(struct sockaddr).
  • 71. Connectionless Service (UDP) Server Client 1. Create transport endpoint: socket() 2. Assign transport endpoint an address: bind() 3. Wait for a packet to arrive: recvfrom() 4. Formulate reply (if any) and send: sendto() 5. Release transport endpoint: close() 1. Create transport endpoint: socket() 2. Assign transport endpoint an address (optional): bind() 3. Determine address of server 4. Formulate message and send: sendto() 6. Release transport endpoint: close() 5. Wait for packet to arrive: recvfrom()