0% found this document useful (0 votes)
16 views52 pages

Unix Unit-V

This document provides an overview of socket programming in Unix, detailing the OSI model, socket definitions, and the various types of sockets (TCP and UDP). It explains the socket interface, address structures, and the system calls used for creating, binding, listening, accepting, and connecting sockets. Additionally, it covers error handling, concurrent server operations, and basic UDP socket input/output functions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views52 pages

Unix Unit-V

This document provides an overview of socket programming in Unix, detailing the OSI model, socket definitions, and the various types of sockets (TCP and UDP). It explains the socket interface, address structures, and the system calls used for creating, binding, listening, accepting, and connecting sockets. Additionally, it covers error handling, concurrent server operations, and basic UDP socket input/output functions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

Unix Programming

Unit - V

Socket Programming
OSI (open system interconnection) Model
Socket
• Definition

– One end-point of a two-way communication link


between two programs running on a network

• A socket is bound to a specific port.


connection

port
Server request
Client

• The client and server can communicate by writing to or


reading from their sockets

3
Socket Interface

socket socket
Application 1 Application 2
interface interface

user user

kernel kernel

Socket Socket

Underlying Underlying
communication communication
Protocols Protocols

Communication
network
4
Socket Address Structures

Socket address structures are passed in 2 directions:

➢ kernel to process (value-result argument)

➢ process to kernel

Different Socket addresses

➢ IPv4 socket address

➢ IPv6 socket address

5
IPv4 Socket Address Structure

It is also called Internet socket address structure sockaddr_in

netinet/in.h, sys/socket.h

struct sockaddr_in {
uint8_t sin_len;
sa_family_t sin_family; /* AF_INET */
in_port_t sin_port; /* 16-bit TCP or UDP port number
network byte ordered */
struct in_addr sin_addr; /* 32-bit IPv4 address network byte
ordered */
char sin_zero[8]; /* unused */ };

6
struct in_addr {
in_addr_t s_addr; /* 32-bit IPv4 address (network byte ordered) */
};

TCP/UDP Ports: Size of IPv4 TCP/UDP ports is 2-byte integer.

sockaddr is generic socket address structure

♦ sin_family = AF_INET
♦ sin_port: port # (512-65535)
♦ sin_addr: IP-address
♦ sin_zero: unused

7
Special IP addresses

IP address Description

0.0.0.0 To source machine only( local machine)

127.0.0.0 Loop back address

INADDR_LOOPBACK To local machine only(source machine)

Doesn’t hit network

255.255.255.255 Limited broadcast (doesn’t pass routers)

INADDR_ANY Socket end point will be bound to all the

systems network interfaces.

8
TCP Socket

bind() socket()

listen() TCP Server


TCP Client

socket() accept()

connection established blocks until connection


connect() (TCP three-way handshake) from client

write()
read()

process request

read() write()

close()
read() close()

9
TCP Server Algorithm

• Create a socket and bind to the well known address for


the service offered.

• Place socket in passive mode.

• Accept next connection request.

• Repeatedly receive requests and send replies

• When client is done, close the connection and return to


waiting for connection requests

10
TCP Client Algorithm

• Find IP address and protocol port number on server.

• Allocate a socket.

• Allow TCP to allocate an arbitrary local port.

• Connect the socket to the server.

• Send requests and receive replies.

• Close the connection.

11
Value result arguments
• bind, connect and sendto pass socket address structure
from process to kernel.
• accept and recvfrom pass socket address structure from
kernel to process.
• In both the cases the arguments are pointer to socket
address structure and length.
• length is passed as a normal variable from process to
kernel.
• It is passed as a pointer from kernel to process.
• Reason for size changing from an integer to be a pointer
to an integer is size is both value and result

12
Value-Result Arguments

13
TCP Socket System calls

IP address + port number

• socket

• bind

• listen

• accept

• connect

14
socket system call

Example:
if (( sd = socket (AF_INET, SOCK_STREAM, 0)) < 0)
perror (“socket call error”);

15
Protocol family constants
Family Description
AF_INET IPv4 protocols
AF_INET6 IPv6 protocols
AF_LOCAL Unix domain protocols
AF_ROUTE Routing sockets
AF_KEY Key socket

Type of socket
Type Description
SOCK_STREAM Stream socket (TCP)
SOCK_DGRAM Datagram socket (UDP)
SOCK_SEQPACKET Sequenced packet socket
SOCK_RAW Raw socket

16
Type Description
SOCK_DGRAM • Fixed length, connectionless, unreliable messages
• No logical connection is required between peers for
them to communicate.
• message oriented
• Aware of message boundaries
SOCK_STREAM • Sequenced, reliable, bidirectional, connection-
oriented
• Logical connection establishment is required between
peers for them to communicate.
• Byte stream oriented
• Unaware of message boundaries

17
SOCK_SEQPACKET • Fixed length, sequenced, reliable, connection-
oriented
• Logical connection establishment is required
between peers for them to communicate.
• Message oriented
• Aware of message boundaries
• SCTP sockets is default in AF_INET family
SOCK_RAW Datagram interface directly to the underlying
network layer.
Applications are responsible for building their own
protocol headers when using this interface, because
the transport protocols(for example: TCP and UDP)
are bypassed

18
Socket Creation
Write a program for creating a socket
#include <sys/types.h>
#include <sys/socket.h>
….
int sockfd;
….
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
….

19
Assigning an address to a socket-- bind
bind Function
int bind (int sockfd, const struct sockaddr *myaddr,
socklen_t addrlen);

Returns 0 if successful or -1 on error

sockfd : a socket descriptor returned by the socket


function.
*myaddr : a pointer to a protocol-specific address.
addrlen : the size of the socket address structure.

20
• The bind() system call is used to assign an IP address to

an existing socket.

• Protocol address: a 32 bit IPv4 address and a 16 bit

TCP or UDP port number.

• If binding is not done then the kernel chooses an

ephemeral port for the socket .

• Error with bind is EADDRINUSE (address already in use)

21
Example :
#include<sys/socket.h>#include<sys/types.h> #include<netinet/in.h>
#include<arpa/inet.h>
struct sockaddr_in sin; int s;
s = socket(AF_INET, SOCK_STREAM, 0);
sin.sin_family = AF_INET;
sin.sin_port = htons(9999);
sin.sin_addr.s_addr = inet_addr(“0.0.0.0”);

if (bind (s, (struct sockaddr *) &sin, sizeof (sin)) != 0)

perror (“bind call error”);

22
listen()
int listen(int sockfd, int backlog)
♦ second argument is maximum number of connections that the kernel
should queue for this socket.

♦ The backlog value is multiplied with 1.5

♦ allows servers to prepare a socket for incoming connections.

♦ places the socket in a passive mode ready to accept connections.

♦ applies only to sockets that have selected reliable stream delivery service.

Commonly it is taken as 5 which allows 8 queued entries on the


system.
23
♦ If queue is full when a client SYN arrives, TCP ignores the

arriving SYN without sending RST. Client resends the SYN,

hopefully finding room on the queue.

♦ If server sends RST then connect on client will generate error.

24
Write a program to change mode of socket to passive
mode
if(listen(sockfd,5)<0)

perror("listen failed :");

exit(1);

printf(“listen successful”);

25
accept() -- TCP Sockets
int accept(int sockfd , struct sockaddr *cliaddr ,
socklen_t * addrlen)

returns 3 values
♦ an integer return code which is either a new socket
descriptor or an error indication.
♦ protocol address of the client process
♦ size of the client address

If we are not interested in having the client address


then last 2 are set to null 0
26
♦ needs to wait for a connection
♦ blocks until a connection request arrives
♦ addrlen is a pointer to an integer;
• when a request arrives, the system fills in argument

cliaddr with the address of the client that has placed

the request and sets addrlen to the length of the

address.

• addrlen is called value result argument.

27
• kernel creates a new connected socket for each client

connection that is accepted, returns the new socket

descriptor. This new descriptor refers to TCP connection

with the client.

• After accept their are 2 socket descriptors.

• When the server is finished serving a given client, the

connected socket is closed.

Write a program for accept system call

28
int fd; /* socket descriptor */
struct sockaddr_in srv; /* used by bind() */
struct sockaddr_in cli; /* used by accept() */
int newfd; /* returned by accept() */
int cli_len = sizeof(cli); /* used by accept() */

/* 1) create the socket */


/* 2) bind the socket to a port */
/* 3) listen on the socket */

newfd = accept(fd, (struct sockaddr*) &cli, &cli_len);


if(newfd < 0) {
perror("accept"); exit(1);
}

29
connect()
Used by TCP client to establish connection

int connect(int sockfd, struct sockaddr *servaddr,


socklen_t addrlen);

30
RTT – round trip time approximately 187ms
Complete queue must have more entries than incomplete

31
32
Kernel maintains 2 queues

• Incomplete connection queue

Contains entry for each SYN that has arrived


from a client for which the server is awaiting
completion of the TCP three-way handshake.

• Completed connection queue

Contains entry for each client with whom the


TCP three-way handshake has completed.

33
Errors

Different types of errors that occur are

• If the client TCP receives no response to its SYN segment,


ETIMEDOUT is returned. After 75 seconds, the error is
returned.

• If server’s response to client ‘s SYN is an RST(reset),


indicates that no process is waiting for connections on the
server host at the port specified called hard error and
ECONNREFUSED is returned to client.

34
RST is sent by server when

• A SYN arrives for a port that has no listening server.

• TCP wants to abort an existing connection.

• TCP receives a segment for a connection that does


not exist.

• If client’s SYN receives destination unreachable from some


intermediate router, called soft error then EHOSTUNREACH
or ENETUNREACH is returned.

35
int fd; /* socket descriptor */
struct sockaddr_in srv; /* used by connect() */

/* create the socket */

/* connect: use the Internet address family */


srv.sin_family = AF_INET;

/* connect: socket ‘fd’ to port 80 */


srv.sin_port = htons(8000);

/* connect: connect to IP Address “128.2.35.50” */


srv.sin_addr.s_addr = inet_addr(“127.0.0.1”);

if(connect(fd, (struct sockaddr*) &srv, sizeof(srv)) < 0) {


perror(”connect"); exit(1);
}
36
Concurrent Server

• Concurrent servers work with fork system call.

• When connection is established accept returns.

• The server calls fork and child process services the

client and parent process waits for another

connection.

• Parent closes the socket since the child handles the

new client.

37
pid_t pid; sfd=socket(..);
bind(…); listen(..);
for(;;)
{
nsfd=accept(..);
pid=fork();
if(pid==0)
{
close(sfd);
}
close(nsfd);

38
server client
Connection Before call to
sfd request connect()
accept

client
server
Connection
sfd connect() After return from
nsfd
accept

39
server(parent)
client
Connection
sfd connect()
nsfd

fork

sfd
nsfd

server(child)

After fork
40
server(parent)
client
sfd connect()

nsfd

server(child)

Close appropriate sockets


41
close() and shutdown()
• close(int socket)
♦ For UDP sockets, this will release the ownership on the
local port that is bound to this socket
♦ For TCP, this will initiate a two-way shutdown between
both hosts before giving up port ownership.
• shutdown(int socket, int how)
♦ If the how field is 0, this will disallow further reading
(recv) from the socket.
♦ If the how field is 1, subsequent writes (send) will be
disallowed. The socket will still need to be passed to
close.

42
Basic UDP Socket I/O
• sendto()
# include <sys/socket.h>
int sendto(int s, void *buf, int len, unsigned int flags,
struct sockaddr *to, int tolen);
Returns: number of bytes sent, -1 on error

• recvfrom()

# include <sys/socket.h>
int recvfrom(int s, void *buf, int len, unsigned int flags,
struct sockaddr *from, int *fromlen);
Returns: number of bytes received, -1 on error

43
flags
Specifies the type of message reception.

Values of this argument are formed by logically OR'ing zero or more


of the following values:
• MSG_PEEK
Peeks at an incoming message.
The data is treated as unread and the next recvfrom() or
similar function shall still return this data.
• MSG_OOB
Requests out-of-band data.
• MSG_WAITALL
On SOCK_STREAM sockets this requests that the function block
until the full amount of data can be returned.

44
UDP Sockets

socket()

bind() UDP Server


UDP Client
recvfrom()
socket()
blocks until datagram
received from client
sendto()

process request

sendto()
recvfrom()

close()

45
UDP Server Algorithm

• Create a socket

• bind to the well-known address for the service offered

• Repeatedly receive requests and send replies.

46
UDP Client Algorithm

• Find IP address and protocol port number on server


• Create a socket
• Send requests and receive replies through socket using
server
• Close the socket

47
Simple UDP Server Example
#include <stdio.h> #include <sys/types.h> #include <sys/socket.h>
#include <netinet/in.h> #include <arpa/inet.h> #include <string.h>
#include <stdlib.h>
int main( ) {
int sfd, cliLen,n;
struct sockaddr_in srvAdr, cliAdr;
char mesg[100];
if((sfd = socket(AF_INET,SOCK_DGRAM,0)) < 0 ) {
perror("Can't open datagram socket \n"); }
srvAdr.sin_family = AF_INET;
srvAdr.sin_addr.s_addr = htonl (INADDR_ANY);
srvAdr.sin_port = htons(8000);
if(bind(sfd,(struct sockaddr*)&srvAdr,sizeof(srvAdr))<0) {
perror ("can't bind local address \n"); }
printf("server waiting for messages \n");

48
while(1)
{
cliLen = sizeof(cliAdr);
n = recvfrom(sfd,mesg,100,0 ,(struct sockaddr*)&cliAdr,&cliLen);
if(n < 0){ perror("recvfrom error \n"); }
if(sendto(sfd,mesg,n ,0,(struct sockaddr *)&cliAdr,cliLen) !=n) {
perror("sendto error \n"); }
printf("Received following message from client %s\n",mesg);
}
}

49
Simple UDP Client Example
#include <stdio.h> #include <sys/types.h> #include <sys/socket.h>
#include <netinet/in.h> #include <arpa/inet.h> #include <stdlib.h>
#include <string.h>
int main( ) {
int sfd,n;
struct sockaddr_in srvAdr;
char txmsg[100], rxmsg[100];
if((sfd = socket (AF_INET,SOCK_DGRAM,0))< 0) {
perror("can't open datagram socket \n"); }

srvAdr.sin_family = AF_INET;
srvAdr.sin_addr.s_addr = inet_addr("127.0.0.1");
srvAdr.sin_port = htons (8000);
printf("Enter message to send :\n");
fgets(txmsg,100,0);

50
n = strlen(txmsg);
if(sendto(sfd,txmsg,n,0,(struct sockaddr *)&srvAdr,sizeof(srvAdr ))!=n)
{
perror("sendto error \n");
}
n = recvfrom(sfd,rxmsg,100,0,NULL,NULL);
printf("n=%d\n",n);
printf("Received following message :%s\n",rxmsg);
}

51
End of Unit -V

52

You might also like