0% found this document useful (0 votes)
31 views

Sockets Introduction

The document discusses socket programming and the client-server model of network interaction. It covers topics like UDP and TCP sockets, blocking and non-blocking sockets, and how servers use reserved ports to provide services to clients.

Uploaded by

ssohan.is21
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views

Sockets Introduction

The document discusses socket programming and the client-server model of network interaction. It covers topics like UDP and TCP sockets, blocking and non-blocking sockets, and how servers use reserved ports to provide services to clients.

Uploaded by

ssohan.is21
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 74

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
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…
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.
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


• 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);
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.
SERVER

Create socket
TCP Client/Server
bind a port to the
socket

CLIENT
listen for incoming
Create socket
connections

accept an
connect to server's
incoming
port
connection

read from the write to the


connection connection

loop loop

write to the read from the


connection connection

close connection
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
Server Side Socket Details
Create socket
int socket(int domain, int type, int protocol)
sockfd = socket(PF_INET, SOCK_STREAM, 0);

bind a port to the int bind(int sockfd, struct sockaddr *server_addr, socklen_t length)
socket
bind(sockfd, &server, sizeof(server));

listen for incoming int listen( int sockfd, int num_queued_requests)


connections
listen( sockfd, 5);

accept an
incoming
int accept(int sockfd, struct sockaddr *incoming_address, socklen_t length)
connection newfd = accept(sockfd, &client, sizeof(client)); /* BLOCKS */

read from the int read(int sockfd, void * buffer, size_t buffer_size)
connection
read(newfd, buffer, sizeof(buffer));

write to the int write(int sockfd, void * buffer, size_t buffer_size)


connection
write(newfd, buffer, sizeof(buffer));
CLIENT
Client Side Socket Details
Create socket
int socket(int domain, int type, int protocol)
sockfd = socket(PF_INET, SOCK_STREAM, 0);

connect to Server int connect(int sockfd, struct sockaddr *server_address, socklen_t length)
socket
connect(sockfd, &server, sizeof(server));

write to the int write(int sockfd, void * buffer, size_t buffer_size)


connection
write(sockfd, buffer, sizeof(buffer));

read from the int read(int sockfd, void * buffer, size_t buffer_size)
connection
read(sockfd, buffer, sizeof(buffer));
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

•socket_init()
Sequence of calls
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
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.
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.


A similar system call
ssize_t recv(int sockfd, void *buf, int len, unsigned int flags);

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.
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 Client

Service (UDP) 1. Create transport


endpoint: socket()
Server
2. Assign transport
1. Create transport endpoint an
address (optional):
endpoint: socket()
bind()

2. Assign transport
endpoint an 3. Determine address
address: bind() of server

3. Wait for a packet 4. Formulate message


to arrive: recvfrom() and send: sendto()

4. Formulate reply (if any) 5. Wait for packet


and send: sendto() to arrive: recvfrom()

5. Release transport 6. Release transport


endpoint: close() endpoint: close()
CONNECTION-ORIENTED
CONCURRENT SERVER
Socket interface
for connection-oriented
concurrent server
Part I
Part II
Part I
Client
and
Server

You might also like