0% found this document useful (0 votes)
61 views55 pages

Ix Ne TW Ork Gra MM Ing: R.H.Goudar Associate Professor, Dept. of CS/IT

This document provides an overview of Berkeley sockets and network programming concepts. It discusses socket system calls like socket(), bind(), connect(), listen(), accept(), and how they relate to establishing connections for both connection-oriented and connectionless protocols. Elementary socket calls like send(), recv(), and close() are also covered. The document describes socket address structures, byte ordering routines, and other network programming basics.

Uploaded by

Ankit Joshi
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
61 views55 pages

Ix Ne TW Ork Gra MM Ing: R.H.Goudar Associate Professor, Dept. of CS/IT

This document provides an overview of Berkeley sockets and network programming concepts. It discusses socket system calls like socket(), bind(), connect(), listen(), accept(), and how they relate to establishing connections for both connection-oriented and connectionless protocols. Elementary socket calls like send(), recv(), and close() are also covered. The document describes socket address structures, byte ordering routines, and other network programming basics.

Uploaded by

Ankit Joshi
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 55

or k

e tw g
N in
ix m m By

n
U ogr a
R.H.Goudar
B.E(CSE),M.Tech(CNE),(Ph.D-CSE)

P r Associate Professor,Dept. of CS/IT,


GEU, Dehradun

rhgoudar@gmail.com
Lesson Plan
1: TCP/IP Basics

1.1 TCP/IP

2: Network Programming
Berkley Sockets
 Introduction –Compare netI/O with fileI/O
 Overview- Socket System Calls for Connection-oriented & Connectionless
 Unix Domain Protocols
 Socket Addresses
 Elementary System Calls
 Client Server Example : SERVER Program CLIENT Program
 Advanced System calls
 Reserved Ports
 Stream Pipes
 Passing File Descriptors.
 Socket options.
 Asynchronous I/O.
 Input/Output Multiplexing.
 Sockets & Signals.
 Internet Superuser.
Elementary Socket System Calls

socket
bind
connect
listen
accept
Iterative & Concurrent Server Examples
send, sendto, recv,recvfrom,close
Byte Ordering Routines
Byte Operations
Address Conversion Routines
Berkeley Sockets
Compare File I/O to Network I/O
1.For a Unix file, there are six system calls for input & output ; open, creat, close,read,
write & lseek.

But the network I/O involves more details & options than file I/O.

i. The typical client-Server relationship is not symmetrical. To initiate a network


connection requires that the program know which role (C-S) it is to play.

ii. A network connection can be connection – oriented or connectionless.

file is connection oriented ,since once we open a connection with another


process, the network I/O on that connection is always with the same process.

With a connectionless protocol, there is nothing like an “open” since every


network I/O operation could be different process on a different host.
Berkeley Sockets Continued….
iii. Names are more important in networking than for file operations.
for ex: a program that is passed a file descriptor by a parent processs can
do file I/O on it without ever needing to know the original name that the file was
opened under.

iv. 5-Tuple Association


{ protocol, local_addr, local_process, foreign_addr, foreign_process} .
There are more parameters that must be specified for a network connection, than
for file I/O.

v. For some communication protocols,record boundaries have significance.The


unix I/O system is stream oriented.

vi. The network interface should support multiple communication protocols.


Ex: XNS(12 bytes),TCP/IP( 4 bytes)
Overview
Server
socket()

bind()

listen()

accept() Client
socket()
Block until connection from client
Connection Establishment
connect()

Data Request
write()
read()
Process request
Data Reply
write() read()
Fig: Socket System calls for Connection-oriented protocol
Server
socket()

bind()
Client
socket()
recvfrom()

bind()
Block until data received
from client

Data (Request)
sendto()

Process request

sendto() Data Reply

recvfrom()
Fig: Socket System calls for Connectionless protocol
Unix Domain Protocols
 Sockets in the domain can only be used to communicate
with processes on the same Unix System.
 4.3 BSD supports Unix Domain Protocols.
 4.3 BSD provides both a connection-oriented & a
connectionless interface to the Unix domain protocols.
 Both can considered reliable, since they exist oonly within
the kernel & are not transmitted across external facilities
such as communication line between systems.
 The Unix domain protocols provide a feature that is not
currently provided by any other protocol family: The
ability to pass access rights from one process to another.
Unix Domain continued….

 The name space used by the unix domain protcols consists of


pathnames. A sample association could by
{unixstr, 0, /tmp/log.01528, 0, /dev/logfile }
The protocol here is unixstr, which stands for “Unix stream” the
connection-oriented protocol. The Local Process is
/tmp/log.01528 & the foreign process is /dev/logfile.
 The local_addr & the foreign_addr as zero, since the pathnames
on the local host are only addresses used in this domain.
 The term unixdg to specify the datagram protocol.
Socket Addresses
Socket address structure definition in <sys/socket.h>
struct sockaddr {
u_short sa_family; /* address family :AF_XXX value*/
char sa_dat[14] ;/* up to 14 bytes of protocol-specific address*/
};
The contents of the 14 bytes of protocol – specific address are interpreted according to the type of
address.
For the Internet family, the following structures are defined in <netinet.h/in.h>

struct in_addr{ /* 32-bit netid/hostid*/


u_long s_addr ;/* network byte ordered*/
};

struct sockaddr_in {
short sin_family;/* AF_INET*/
u_short sin_port;/* 16-bit port number */
struct in_addr sin_addr; /* 32-bit netid/hostid*/
/* network byte ordered */
char sin_zero[8]; /* unused*/
};
Socket Address Structures

struct sockaddr_in struct sockaddr_ns


family family
2-byte port
4-byte
4-byte netID
netID, hostId

6-byte host ID

(unused) 2-byte port


number
(Unused)

Fig: Socket address structure for Internet and XNS Families


Socket Address Structures Continued..

The network system calls take 2 arguments :


1. The address of the generic sockaddr structure
2. The size of the actual protocol-specific structure.

struct sockaddr_in serv_addr;


/* Internet-specific addr struct */

Type Casting to a Generic Address Structure.


Elementary Socket System Calls
socket System Call
#include<sys/types.h>
#include<sys/socket.h>
int socket(int family,int type,int protocol);
the family is
AF_UNIX Unix internal protocols
AF_INET Internet protocols
AF_NS Xerox NS protocols
AFAddress family.
The socket type is one of the following :
SOCK_STREAM Stream Socket
SOCK_DGRAM Datagram socket
SOCK_SEQPACKET sequenced packet socket
Socket System Call Continued..

The protocol argument to the socket system call is typically set to 0 for must user
applications. There are specialized applications, however, that specify a protocol
value to use a specific protocol. The valid combinations are shown in fig below.
family type protocol Actual protocol
AF_INET SOCK_DGRAM IPPROTO_UDP UDP
AF_INET SOCK_STREAM IPPROTO_TCP TCP
AF_INET SOCK_DGRAM IPPROTO_UDP ICMP
AF_NS SOCK_STREAM NSPROTO_SPP SPP
AF_NS SOCK_SEQPACKET NSPROTO_SPP SPP
AF_NS SOCK_RAW NSPROTO_ERROR ERROR protocol

Fig: Combination of family,type & protocol.


Socket system calls & association elements

Protocol local_addr, local_process foreign_addr, foreign_process


Connection-oriented server socket() bind() listen(), accept()
Connection-oriented client socket() connect()
Connection-less server socket() bind() recvfrom()
Connection-less client socket() bind() sendto()
Fig: Socket system calls & association elements

The Socket system call specifies is one element of this tuple, the protocol.
The Socket system call returns a small integer value, similar to a file
descriptor.
bind system call
bind System call
The bind system call assigns a name to an unnamed socket.
#include<sys/types.h>
#include<sys/socket.h>

int bind (int sockfd,struct sockaddr *myaddr, int addrlen);


The second argument is a protocol specific address & the third argument is the size of this address structure.
Three uses of bind.
1. Servers register their well-known address with the system.It tells the system “this is my address & any messag
received for this address are to be given to me. Both connection oriented & connectionless servers need to this before accepting client requets.
2. A client can register a specific address for itself.
3. A connectionless client needs to assure that the system assigns it some unique address, so that the other end has a valid return address to
send its responses to.
The bind system call fills in the local_addr & local-process of 5 tuple association.
Connect System Call
A client process connects a socket descriptor following the socket system call to
establish a connection with a server.
#include<sys/types.h>
#include<sys/socket.h>
int connect( int sockfd, struct sockaddr *servaddr, int addrlen);
The connection typically causes these four elements of the association 5-
tuple to be assigned: local_addr, local_process ,foreign-addr & foreign-process.

The connect & bind system calls require only the pointer to the address structure
& its size as arguments, not the protocol;
listen system call
This system call is used by a connection-oriented server to indicate that it is
willing to receive connections.

int listen(int sockfd , int backlog);

It is executed after both the socket & bind system calls & immediately
before the accept system call.

The backlog argument specifies how many connection requests can be


queued by the system while it waits for the server to execute the system
call.(Maximum is 5)
accept System call
After a connection-oriented server executes the listen system call ,an actual
connection from some client process is waited for by having the server execute
the accept system call.
#include<sys/types.h>
#include<sys/socket.h>

int accept(int sockfd, struct sockaddr *peer, int *addrlen);


accept takes the first connection request on the queue & creates another socket with the
same properties as sockfd.If there are no connection requests pending, this call blocks
the caller until one arrives.
The peer & addrlen arguments are used to return the address of the connected peer
process(the client). addrlen is called a value-result argument.
This system call returns up to three values :
1. an integer return code that is either an error indication or a new socket descriptor
2. the address of the client process(peer) &
3. the size of this address.(addrlen)
Concurrent Server example
int sockfd, newsockfd;
if(( sockfd=socket(…))<0)
err_sys(“socket error”);
if( bind(sockfd,…)<0)
err_sys(“bind error”);
if( listen(sockfd,5)<0)
err_sys(“listen error”);
for(;;){
newsockfd=accept(sockfd,…); /* blocks */
if(newsockfd<0)
err_sys(“accept error”);
if(fork()==0) {
close(sockfd); /* child */
doit(newsockfd); /* process the request */
exit(0);
}
close(newsockfd); /* parent */
}

Most Connection-Oriented servers are Concurrent servers & not iterative servers
Iterative Server example
int sockfd, newsockfd;
if(( sockfd=socket(…))<0)
err_sys(“socket error”);
if( bind(sockfd,…)<0)
err_sys(“bind error”);
if( listen(sockfd,5)<0)
err_sys(“listen error”);
for(;;){
newsockfd=accept(sockfd,…); /* blocks */
if(newsockfd<0)
err_sys(“accept error”);
doit(newsockfd); /* process the request */
close(newsockfd);
}
send,sendto,recv & recvfrom System Calls
Similar calls to the std. read & write system calls.
#include<sys/types.h>
#include<sys/socket.h>
int send( int sockfd, char * buff, int nbytes, int flags);
int sendto( int sockfd, char *buff, int nbytes,int flags, struct sockadrr *to, int addrlen);
int recv( int sockfd, char *buff, int nbytes, int flags);
int recvfrom( int sockfd, char *buff, int nbytes, int flags, struct sockaddr *from, int
*addrlen);
The flags argument is either zero, or is formed by or’ing one of the following
constants.
MSG_OOB send or receive out-of-band data.
MSG_PEEK peek at incoming message.(recv or recvfrom)

Close System call


int close(int fd);
Byte Ordering Routines
The following four functions handle the potential byte differences between
different computer architectures & different network protocols.

#include<sys/types.h>
#include<netinet.h>
u_long htonl (u_long hostlong);
u_short htons(u_short hostshort);
u_long ntohl( u_long netlong);
u_short ntohs( u_short netshort);

These functions were designed for the Internet protocols.


htonl convert host-to-network, long integer
htons convert host-to-network, short integer
ntohl convert network-to-host, long integer
ntohs convert network-to-host, short integer.

short – 16 bits
long – 32 bits
Byte Operations

bcopy(char *src, char *dest, int bytes);

bzero( char *dest, int nbytes);

int bcmp( char *ptr1, char *ptr2, int bytes);


Address Conversion Routines
#include <sys/socket.h>
#include <netinet/in.h>
#include<arpa/inet.h>
unsigned long inet_addr(char *ptr);
inet_addr converts string in dotted-decimal notation to a 32 bit internet address.

char *inet_ntoa(struct in_addr inaddr);


Reverse Conversion
Server Program

#include<sys/types.h>
Socket
#include<sys/socket.h>
#include<stdio.h>
#include<netinet/in.h>
Address Conversion Routines
#include<arpa/inet.h>

#define SERV_TCP_PORT 5005


#define SERV_HOST_ADDR “190.190.0.0”
#define MAXLINE 512
Server Program continued…
main()
{
int sockfd,newsockfd,clilen,childpid;
struct sockaddr_in cli_addr,serv_addr;
char buf[256];
// open a TCP socket(a internet stream socket)

if((sockfd=socket(AF_INET,SOCK_STREAM,0))<0)
printf(“Server can’t open stream socket\n”);
bzero((char *)&serv_addr,sizeof(serv_addr));
Server Program continued…
serv_addr.sin_family=AF_INET;
serv_addr.sin_port=htons(SERV_TCP_PORT);
serv_addr.sin_addr.s_addr=inet_addr(SERV_HOST_ADDR
);
//inet_addr- converts a dotted-decimal notation to a 32 bit
Internet address.

if(bind(sockfd,
(struct sockaddr *)&serv_addr,sizeof(serv_addr))<0)
//bind local addrs so that client can send to us
printf(“Server can’t bind local addr\n”);
listen(sockfd,1);
Server Program continued…
for(;;)
{
//wait for a connection from a client process-this is an example of
concurrent server.
clilen=sizeof(cli_addr);
newsockfd=accept(sockfd,(struct sockaddr *) &cli_addr, &clilen);
if(newsockfd<0)
printf(“Server accept error\n”);
if((childpid=fork())<0)
printf(“Server fork error \n”);
else
if(childpid==0)
//child process
Server Program continued…
printf(“ pid is %d\n”,childpid);
close(sockfd);
//close original socket.
read( newsockfd,buf,6);
buf[6]=‘\0’;
printf(“Server reads ‘%s’ \n”,buf);
write(newsockfd,”HELLO I RECEIVED”,16);
exit(0);
}
close(newsockfd);
//parent process
}
}
Client Program

#include<sys/types.h>
Socket
#include<sys/socket.h>
#include<stdio.h>
#include<netinet/in.h>
Address Conversion Routines
#include<arpa/inet.h>

#define SERV_TCP_PORT 5005


#define SERV_HOST_ADDR “190.190.0.0”
#define MAXLINE 512
Client Program continued…
main()
{
int sd;
struct sockaddr_in serv_addr;
char buf[256];
// open a TCP socket(a internet stream socket)

if((sd=socket(AF_INET,SOCK_STREAM,0))<0)
printf(“Server can’t open stream socket\n”);
bzero((char *)&serv_addr,sizeof(serv_addr));
Client Program continued…
serv_addr.sin_family=AF_INET;
serv_addr.sin_port=htons(SERV_TCP_PORT);
serv_addr.sin_addr.s_addr=inet_addr(SERV_HOST_ADDR);
//inet_addr- converts a dotted-decimal notation to a 32 bit Internet
address.
If(connect(sd,(struct sockaddr *) &serv_addr, sizeof(serv_addr))<0)
printf(“Client :can’t connect to server \n”);
write(sd,”hi guy”,6);
read(sd,buf,16);
buf[16]=‘\0’;
printf(“ Client recieves %s\n”,buf);
}
Advanced Socket System Calls

 readv & writev System Calls

 sendmsg & recvmsg System Calls.

 getpeername System Call.

 shutdown System Call


readv & writev System Calls
#include<sys/types.h>
#include<sys/uio.h>
int writev(int fd, struct iovec iov[],int iovcount);
int readv(int fd,struct iovec iov[], int iovcount);
Two system calls structure defined in <sys/uio.h>
struct iovec{
caddr_t iov_base;/*starting address of buffer */
int iov_len;/* size of buffer in bytes */
};
sendmsg & recvmsg System Calls

#include<sys/types.h>
#include<sys/socket.h>
int sendmsg(int sockfd, struct msghdr msg[], int flags);
int recvmsg(int sockfd, struct msghdr msg[], int flags);
msghdr structure header defined in <sys/socket.h>
struct msghdr{
caddr_t msg_name;/* optional address */
int msg_namelen; /*size of address */
struct iovec *msg_iov;
int msg_iovlen;
caddr_t msg_accrights;
int msg_accrightslen;
};
getpeername System Call

#include<sys/types.h>
#include<sys/socket.h>
int getpeername(int sockfd, struct
sockaddr *peer, int *addrlen);
getsockname System Call

#include<sys/types.h>
#include<sys/socket.h>
int getsockname(int sockfd, struct
sockaddr *peer, int *addrlen);
shutdown System Call

int shutdown(int sockfd, int howto);


howto argument ->0,no more data can be
received on the socket.
->1 no more output to be
allowed on the socket.
->2 Both sends & receives to
be disallowed.
Reserved Ports
 2 ways for an process to assign an portno.
1.The Process can request for a specific port.
2. The process can let the system automatically assign
a port.
 int rresvport(int *aport);
 Fig below summarizes the assignments of ports in the Internet &
XNS domain.(

socket() Internet XNS


Reserved ports 1-1023 1-2999
Ports automatically assigned by the system 1024-5000 3000-65535
Ports assigned by rresvport() 512-1023
Stream Pipes

#include<sys/types.h>
#include<sys/socket.h>
int s_pipe(intfd[2])
`{

return(socketpair(AF_UNIX,SOCK_STREAM,0,
fd));
}
Passing File Descriptors
Process Table Entry
f
dfd0
0
fd1

fd2 file table


i-node table
... Current file position
i-node
information
i-node ptr
Process Table Entry

fd0
fd1
fd2

...
Fig: Sharing a file table entry between two processes
Socket Options

 getsockopt & setsockopt

 the fcntl system call.


.
getsockopt & setsockopt System Calls

#include<sys/types.h>
#include<sys/socket.h>
int getsockopt( int sockfd, int level, int optname,
char *optval, int *optlen);

int setsockopt( int sockfd, int level, int optname,


char *optval, int optlen);
Level optname
IPPROTO_IP IP_OPTIONS

IPPROTO_TCP
TCP_MAXSEG Ethernet ->1024bytes
TCP_NODELAY
TCP_NODELAY :Send the data as
soon as possible
optval specifies the DataType
optlen specifies the length of the optval
Level-> XNS or TCP/IP
fcntl System Call
 Users can use fcntl to assign multiple file descriptors to reference
the same file.
#include<fcntl.h>
int fcntl(int fdesc, int cmd,…);
The cmd argument specifies which operations to perform on
a file referenced by the fdesc argument.
Cmd values are F_GETOWN,F_SETOWN,F_GETFL & F_SETFL.
F_SETOWN command sets the processID to receive the SIGIO
signals for the socket associated with fd.
F_GETOWN returns the value of fcntl.
F_SETFL :
F_GETFL : based on flags
FNDELAY :
This option designates the socket as “nonblocking”.An
I/O request that cannot complete & return is made to
the caller immediately with the errno.
FASYNC:
This option allows the receipt of asynchronous I/O
signals.The SIGIO signal is sent to the process group
of the socket when data is available to be read.
Asynchronous I/O
 Asynchronous I/O allows the process to tell the kernel to notify it
when a specified descriptor is ready for I/O.It is called the signal-
driven I/O.
 The notification from the kernel to the user process takes place
with a signal, the SIGIO signal.
 To do asynchronous I/O, a process must perform the following
three steps:
1.The process must establish a handler for the SIGIO signal.This is
done by calling the signal call.
2. The process must set the process ID to receive the SIGIO
signals.This is done with the fcntl system call, with the
F_SETOWN command.
3. The Process must enable asynchronous I/O using the fcntl
system call, with the F_SETFL command & the FASYNC
argument.
Input/Output Multiplexing
Consider a process that reads input from one source. It opens two
sockets one to receive print requests from processes on the same
host & to receive print requests from processes on other hosts.
Since it doesn’t know when requests will arrive on the two sockets, it
can’t start a read on one socket, as it could block while waiting for a
request on that socket, & in the mean time a request can arrive on
the other socket.
Techniques available to handle multiplexing of different I/O Channels
1.It can set both sockets to nonblocking, using either the FNDELAY flag
to fcntl.The process has execute a loop that reads from each socket
& if nothing is available to read, wait some amount of time before
trying the reads again.This is called polling.
Polling can waste computer resources, since most of the time there
is no work to be done.
2.The process can fork one child process to handle each
I/O channel.
3. Asynchronous I/O can be used.
4.Another technique is provided with the select system call.
This system call allows the user process to instruct the
kernel to wait for any one of multiple events to occur & to
wake up the process only when one of these events
occurs.
The prototype for the system call is
#include<sys/types.h>
#include<sys/time.h>
int select(int maxfdp1, fd_set *readfds, fd_set *writefds,
fd_set *exceptfds, struct timeval *timeout);
struct timeval{
long tv_sec; /*seconds */
long tv_usec; /* microseconds */
}l
Sockets & Signals

There are three signals that can be generated for a socket


1. SIGIO : This signal indicates that a socket is ready for
asynchronous I/O.
2. SIGURG: This signal indicates that an urgent condition
(out-of-band data) on a socket.
3. SIGPIPE: This signal indicates that we can no longer
write to a socket,pipe,or FIFO.
Internet Superserver

BSD release provided Internet Superserver :


the inetd process.
Features :
1.It allows a single process (inetd) to be waiting to service
multiple connection requests, instead of one process for
each potential service. This reduces the total number of
processes in the system.
2. It simplifies the writing of the daemon processes to handle
the requests, since many of the start-up details are handled
by inetd.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy