Upload
karthik-ravi
View
115
Download
5
Tags:
Embed Size (px)
Citation preview
1
SUB: IT1352 -NETWORK PROGRAMMING AND MANAGEMENT
UNIT IELEMENTARY TCP SOCKETS
1.1 Introduction Network
Network is an interconnection of computers, capable of communicating with each other.
Communication means sharing of physical resources.
Network is classified into two groups – LAN & WAN.
Topology refers to the physical arrangement of network components.
Protocol is a set of ruled and accepted conventions for communication.
Network use functional modules called layers.
ISO / OSI Network Model
It consists of 7 layers. Each layer should perform well-defined function.
1. Application layer – User interface to network services.
2. Presentation layer – Translate data formats, data compression.
3. Session layer – Establish / Maintain / Terminate a connection.
4. Transport layer –Flow control ensures reliable delivery of packets in Sequences.
5. Network layer – Translation of logical & physical addresses.
6. Datalink Layer – Converts frames into bits & bits into frames.
7. Physical layer – Transportation of raw data or binary data.
Layers of TCP/IP Protocol
Application Telnet, FTP, SNMP, SMTP, TFTP DNS
Transport TCP, UDP
Internet IP,ICMP,IGMP,ARP.RARP
Network Access (NIC)LAN,X.25
Table 1.1 Four Layers of the TCP/IP protocol suite
1
Fig: 1.1 Layers of TCP/IP
Model
1.2 Introduction to Socket Programming
Socket is a primitive that create a new communication end points, allocates table space for
it within the transport entity.
Socket allows communication among different processes in different machines.
We write a network programs using API’s. There are two types of API.
a. Socket b. XTI – Open Transport Interface.
Network application can be divided into two pieces.
a. Client. b. Server
Communication Link
Client can communicate with one server at a time.
Server can communicate with many clients at a time.
Types of communicating services
1. Connecting oriented services Eg: TCP
2. Connectionless services Eg: UDP
“Internet” refers to networks that are interconnected by TCP / IP. TCP / IP is the foundation of all of these
varied networks
.1.7.3 OVERVIEW OF TCP/IP
1. IPV4: Internet protocol, version 4, denotes IP workhorse protocol of Internet protocol suite since 1980’s.
Uses 32 – bit addresses.IPV4 provides packet delivery service for TCP UDP, ICMP & IGMP.
.2. IPV6: Internet protocol, version 6, designed in mid - 1990’s as a replacement of IPV4. Major change is
larger address. Comprising 128 bits to deal with Internet It provides packet delivery for TCP,
UDP, ICMPV6.
Application Program
TCP UDP
Physical and Datalink layer
IP
Client Server
1
3 .TCP: Transmission Control protocol. Connection oriented that provides reliable, full duplex byte stream
. for a user process. TCP sockets are examples for stream sockets. It takes care of acknowledgement,
timeouts, and retransmissions. Most Internet application protocol use TCP can use either IPV4 / IPV6.
4. UDP: User Datagram Protocol. Connectionless & UDP Sockets are examples for datagram sockets. . .
. There is no guarantee that UDP datagram’s reach their destination, it can use either IPV4 / IPV6.
5. ICMP: Internet Control Message Protocol. Handles error and control information between
routers and hosts. These messages are normally generated and processed by TCP / IP networking
software itself, not by user processes.
6. IGMP: Internet Group Management Protocol .Used with multicasting, optional with IPV4.
7. ARP: Address Resolution Protocol. Maps IPV4 address into a hardware address (Ethernet address).
Normally used on broadcast networks like Ethernet, token ring and FDDI.
8.RARP: Reverse Address Resolution Protocol. Maps hardware address into IPV4
address. Sometimes used when diskless node like X terminal is booting.
9 ICMPV6: Internet Message Control Message Protocol version 6.Combines the functionality of ICMPV4,
IGMP & ARP.
10. BPF: This interface provides access to the data link for a process. It is normally found on Berkeley-
derived kernels.
11. DLPI: Data Link Provider Interface. This interface provides access to the Data link.
Fig 1.2 Overview of TCP/IP
The left most application, tcp dump, communicate directly with the data link using either BPF (BSD packet filter or DCPL (Data link provider – Interface)
Dashed line indicates sockets or XTI.The interface to either BPF or DCPI does not use sockets or XTI.
1
UDP: USER DATAGRAM PROTOCOL:-
It is a simple transport layer protocol. The application writes a datagram to UDP Socket, which is
encapsulated as either IPV4 datagram or IPV6 datagram, which is then sent to its destination. It adds no
reliability, flow control or error recovery. If we want to be certain that a datagram reaches its destination, we
must build lot of features into our application like acknowledgments, retransmission.
Source port Destination port Length Checksum
Field DescriptionSource port Port number of source portDestination port Port number of destination portLength Total length of the datagramChecksum Used to detect errors for the entries of the datagram.
Each UDP datagram has a length and we consider a datagram as a record. If the datagram reaches its
final destination correctly then the length of the datagram, is passed to the receiving application. UDP provides
connectionless services as there need not be any long-term relationship between a UDP client and server.
Allows application to exchange message over the network within a minimum of protocol overhead UDP .It uses
16-bit Source port and Destination port number.
TCP -Transmission Control Protocol TCP provides a reliable data delivery, connection oriented, and byte stream protocol. It is full
duplex stream sockets and takes care of details such as acknowledgement, retransmission & timeouts. TCP
client establishes a connection with a given server, exchanges data with that server across the connection. TCP
contains algorithms to estimate the Round-trip time between a client & server dynamically so that it knows how
long to wait for an acknowledgement. It also sequences the data by associating a sequence number with every
byte it sends.
Client Server
socket SYN J socket,bind,listen,accept(blocks)
connect(blocks)
SYN K, ack J+1
Connect returns
Ack K+1,
Accept returns read(blocks)
Fig 1.3 TCP 3 - Way Hand Shake Method
1
TCP connection is established by three-way handshake signal.
1. Client begins the connection by sending SYN segment & synchronizes sequences number to the
server.
2. Server must acknowledge the clients SYN signal that is ACK segment.
3. Client sends ACK with data.
Client sending connect function to server is called active open.
Server prepared to accept an incoming connection is called passive open.
TCP Options
Each SYN contain TCP option.
1. MSS Option – (Maximum Segment Size). It announces Maximum amount of data willing to accept.
2. Window scale option – For larger window to obtain the maximum throughput.
3. Timestamp Option – To prevent possible data corruption.
TCP Connection Termination
It takes four segments to terminate the connection.
Client Server
close(active close) FIN M
(Passive close)
Ack M+1 read returns 0
FIN N
close
Ack N+1
Fig 1.4 TCP Connection Terminations
Client sends FIN segment to the server is called active close. Server received FIN is called passive close.
1
1
ICMP- Internet Control Message Protocol
ICMP sends error messages, control information for TCP / IP. ICMP messages are transmitted within
IP packets.
ICMP Message Format
8 bit type 8 bit code 16 bit Checksum (Contents depends on type & code)
1
ICMP Messages
address mask request and reply
Timestamp request and reply
Port unreachable.
ICMP Control Messages
Flow control.
Redirecting Routes.
Checking Remote hosts.
IGMP - Internet Group Management Protocol
IGMP is used by host & routers to support multicasting. It tells the system physical connection, which
host currently belonging to the multicast group. A host doesn’t send a report when processes leave a group.
IGMP Message Format
Fields Description
Version 1Type 1 Query sent by a multicast router, Type 2 Response sent by a host.
Checksum Error calculation.Group address Represents address of a multicast group.
ARP – Address Resolution Protocol
ARP maintains a table of translations between IP address and physical addresses. This table is built
dynamically. It maps IP address with corresponding physical address. It receives request of IP address, and
it checks in its table.
ARP Message Format
Ethernet Destination Address
Ethernet Source Address
Frame Type
Hard Type
ProtoType
Hard Size
ProtoSize
OP Sender Ethernet Address
Sender IP Address
Target Ethernet Address
Target IP Address
Ethernet Data 28 byte ARP request/reply
6 6 2 2 2 1 1 2 6 4 6 4 Fig 1.5 ARP Message format
IGMP Version 1 IGMP Type (1/2) Unused Checksum 32 bit group address
1
Fields Description
Frame type Specifies type of data that follows
Hardware type & prototype Used to describe the packets
Hard Size & Proto Size Size of hardware addresses & protocol addresses
OP Specifies the operation. Value 1 – ARP request, Value 2 – ARP response,
Value 3 – RARP request, Value 4 – RARP Response.
RARP: Reverse Address Resolution Protocol
It converts the physical address into IP address. Frame type for ARP is 0X0806.Frame type for RARP is
0X8035.
ICMPV6
It combines the functionality of ICMPV4, ARP and IGMP.
BPF & DLPI
BSD packet Filter – This interface provides access to the data link for a process.
Data link Provider Interface – It also provides access to the data link.
TCP DUMP
It examines all the packets and IP header. It is also determines the content of packet.
Trace Route
It is a debugging tool. It traces the route for IP datagram from one host to another.
Fig 1.6 Trace Route Message format Trace Route is developed for three reasons:
1. Record route option
2. Sender enables one-way option
3. Rooms allocated to handle most routes.
It maintains two fields.
1. ICMP field count routers in the path
2. TTL – Time to – live, TTL is 0 then code is 0. Error messages are specified code 1.
IP header +8 byte data
Type(11) Code(0/1) Checksum Unused (must be 0)
1
PING Program It is testing tool. It tests whether the destination host is reachable. It measures Round Trip Time to the host. RTT is a time taken to response for the request. It also test network connection, independent of application of the original problem detected. Ping program is very useful tool to connect with remote host.
Fig 1.7 PING Program Message format
Remote host IP process is identified. Sequences No is initialized to 0. When request is reached at remote
host it increased by 1.Optional data must be echoed by the server.
M-routed Program It performs both multicast tunneling and Route propagation.
1.4 SOCKET ADDRESS STRUCTURE
Each supported protocol suite defines its own socket address structure. Socket functions require a
pointer to a socket address structure as an argument. The names of these structure begins with sockaddr_
1.4.1 IPV4 Socket Address Structure It is commonly called an “Internet Socket Address Structure”. It is defined by sockaddr_in including
the #include <netinet / in. h > header.
IPV4 Socket Address Structure POSIX. 1g definition.
struct in_addr {
in_addr_t s_addr; /* 32 – bit IPV4 address*/
}; /* network byte ordered*/
struct sockaddr_in{
unit8_t sin_len; /* length of the structure*/
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); /* unsued*/
};
struct in_addr contains 32 bit IPV4 address as an argument. IPV4 address is in the form of Network byte
ordered.
Optional data
Type Code Checksum Identifier Sequence Number
1
First member of posix.1g is length. It defined length of socket address is 16 byte. This value is used only
within the kernel routines.
sa_family_t can be any unsigned integer type. IPV4 family is indicated by AF-INET.
sin_port must be any unsigned integer type of at least 16 bits. It may be a TCP or UDP port Number.
It is stored in network byte order.
sin_zero(8) Almost all implementations add the sin_zero member. So that all socket address
structures are atleast 16 bytes in size. It is unused always set to 0.
32 bit IP address can be used in two different ways.
1. sin_addr IPV4 32 bit address as an in_addr structure.
2. s_addr IPV4-32 bit address as an in_addr_t structure
IPV4 Header
Version Header
Length
Type of service Total Length in byte
Identification 0
D
F
M
F
Fragment
offset
Time to Live Protocol Header Checksum
32 bit source IPV6 address
32 bit destination IPV6 address
Options(if any)
Data
Some of the POSIX defined data types.DATA TYPE DESCRIPTION HEADER
int8_t signed 8-bit integer <sys/types,h>
unint8_t unsigned 8-bit integer <sys/types,h>
int 16_t Signed 16- bit integer <sys/types,h>
uint 16_ t Unsigned 16 -bit integer <sys/types,h>
Int32_t signed 32 bit- integer <sys/types,h>
uint 32_t Unsigned 32- bit integer <sys/types
sa_family_t Address family of socket address structure
<sys/socket.h>
socklen_t Length of the socket address structure <sys/socket.h>
in_addr_t IPV4 address <sys/socket.h>
in_port_t TCP or UDP port <sys/socket.h>
1
Socket address structures are used only on a given host. The structure itself is not communicated
between different hosts although certain fields are used for communication.
1.4.2 GENERIC SOCKET ADDRESS STRUCTURE
Socket address structure is passed by reference to socket function. Socket function takes one of the
pointer arguments to the socket address structure. The problem is how to declare the type of pointer, to recover
this problem POSIX defines generic socket address structures.
struct sockaddr{
unit8_t sa_len; /*address family:AF_xxx value*/
sa_family_t sa_family; /*protocol – specific address*/
char sa_data[14];
};
These generic socket address structure is to cast pointers to protocol specific structures. Eg: int bind
(sockfd,(struct sockaddr *)&serv,sizeof(serv));
1.4.3 IPV6 SOCKET ADDRESS STRUCTURE It is included in <netinet/in.h> header
struct in6_addr{ unit8_t s6_addr[16]; /*128-bit IPV6 address */ }; /*network byte order*/
#define SIN6_LEN struct sockaddr_in6{
unit8_t sin6_len; /*length of this struct(28)*/
sa_family_t sin6_family; /*AF_INET6*/
int_port_t sin6_port; /*transport layer port*/
/*network byte ordered*/unit32_t
sin6_flowinfo; /*flow information, undefined*/
struct in6_addr sin6_addr; /*IPV6 address*/
/*network byte ordered*/
unit32_t sin6_scope_id; /*set of interfaces for a scope*/
};
1
IPV6 Header
Version Priority Flow Label
Payload Length Next header Hop
Limit
128 bit source IPV6 address
128 bit destination IPV6 address
Flow information member is divided into three fields 24bit flow label
4 bit priority
4 bit reserved
1.4.4 COMPARISON OF SOCKET ADDRESS STRUCTURE
IPV4 and IPV6 are fixed length. UNIX domain and data link are variable length. Variable length means
it pass the pointer as an argument for socket address structure with the length argument.
1 byte for length
1byte for family
IPV4 IPV6 UNIX Datalink Storage
sockaddr_in{} sockaddr_in{} sockaddr_in{} sockaddr_in{} sockaddr_in{}
Fixed –length
(16 bytes)
Fixed length
(28 bytes)
variable –length variable –length
longest on system
1.4.5 VALUE RESULT ARGUMENT
The three functions bind, connect, sendto pass Socket Address Structure from process to kernel. It sends two
arguments, one is SAS pointer and other is value of length
length AF_
INET
16 bit port #
32 bit
IPV4 address
Unused
length AF_INET
6
16 bit port #
32 bit flow label
128 bit IPV6
address
32 bit scope ID
length AF_Local
pathname
(up to 104 bytes)
length AF_XXX
Opaque
length AF_Link
Interface index
Type name len
Addr
len
sel len
Interface name
and link layer
address
1
Syntax:
struct sockaddr_in serv;
connet(sockfd, (SA *) &serv, sizeof(serv));
The four functions accept, recvfrom, getsockname, getpeername pass SAS from the kernel to process.
Two arguments of these functions are the pointers. Here the length isalso pointer that is result. It tells how
much information the kernel actually stores in the structure. It is used in variable length structure.
User Process
Protocol Ad Fig 1.8 SAS passed from process to kernel
Syntaxstruct sockaddr_in cli;
socklen_t len;
len=sizeof(cli);
getpeername(unixfd, (SA *) &cli,&len);
Protocol address
Fig 1.9 SAS passed from Kernel to Process
When using value-result arguments for the length of SAS, if socket address fixed, value returned by the kernel
will be fixed. For variable length SAS, value returned can be less than maximum size of the structure.
1.5 BYTE ORDERING FUNCTIONS
int
Value Result
Kernel
Length
Socket Address Structure
int *
Value Result
Kernel
Length
Socket Address Structure
1
Consider a 16 bit integer made up of 2 bytes; there are 2 ways to store the 2 bytes in memory.
1. Lower order byte at stating address, little endian byte order
2. Higher order byte at starting address, big endian byte order
address A+1 increasing memory address address A
LEBO
BEBO
increasing memory address
In the figure, the increasing memory address is going from right to left in the top and left to right in the
bottom. MSB (most significant bit) as the leftmost bit of 16 bit value and LSB (Least significant bit) as the
rightmost bit. No standard between 2 byte orderings and system use both formats. We refer to the ordering used
by a given system as host byte order
Program to determine host byte order
#include “unp.h”intmain(int argc,char **argv){
union{short s;char c[sizeof(short)];
}un;un.s=0x0102;
printf(”%s”,CPU_VENDOR_OS);
if(sizeofshort==2){
if(un.c[0]==1&&un.c[1]==2)
printf(“Big Endian”);
else if(un.c[0]==2 &&un.c[1]==1)
printf(“Little Endian”);
else
High odder byte Low byte order
MSB 16 bit value LSB
High order byte Low order byte
1
printf(“Unknown”);
else
printf(“sizeof(short)=%d,sizeof(short)”);
exit(0);
}
C[0]address of A, C[i]address of A+1
CPU_VENDORidentifies CPU type, vendor and OS release
Network protocol specifies network byte order; the IP uses big endian byte ordering for multibyte
integers. The following 4 functions are used to convert between 2 byte orders
# include <netinet/in.h>
unit16_t htons (unit 16_t host16bitvalue);
unit32_t hton1(unit32_t host32bitvalue);
Both return: value in network byte order
unit16_t ntohs (unit16_t net16bitvalue);
unit32_t ntohl (unit32_t net32bitvalue);
Both return: value in host byte order
Here, H host, n network, s short, l long
On those systems that have the same byte ordering as the internet protocols, these. The 4 functions
usually defined as null macros.
1.6 ADDRESS CONVERSION FUNCTIONS
There are 2 groups of address conversion functions are available. They convert Internet addresses between
ASCII string and network byte ordered binary values.
1.inet_aton, inet_ntoa, inet_addr Convert an IPV4 addressed between a dotted- decimal string
(206.62.266.33) and its 32 – bit network byte ordered binary value.
2. inet_pton, inet_ntop handle both IPV4 and IPV6 addresses.
inet_aton, inet_ntoa, inet_addr
#include <arpa /inet.h>
1
int inet_aton (const char *strptr, sturct inaddr * addrptr);
Returns : 1 if string valid, 0 on error
in_addr_t inet_addr (const char * strptr);
Returns: 32 bit binary network byte ordered IPV4 address;
INADDR –NONE if error
char * inet _ntoa (struct in-addr inaddr);
Returns: pointer to dotted-decimal string
inet _ addr
Does the same function of inet_aton, returning 32 bit binary network byte order value as return value.
Problem with this function is dotted decimal string cannot be handled; binary value indicates the failure
of the function.
inet_ntoa Converts 32-bit binary network byte ordered IPV4 address into its corresponding dotted decimal string.
INET_PTON and INET_NTOP FUNCTIONS
` These 2 functions work with both IPV4 and IPV6 addresses.
#include <arpa /inet.h>
int inet _pton (int family, const char * strptr, void * addrptr);
Returns: 1 if OK, 0 if input not a valid presentation format, - 1 on error
const char* inet_ntop (int family, const void *addrptr,
char *strptr, size_t len);
Returns: pointer to result if OK, NULL on error.
Here, n numeric, p presentation
Family arguments for both the functions can be either AF-INET or AF-INET6, if family is not present
both function return -1 with errno set to EAFNO SUPPORT.
inet _pton: Converts string pointed by strptr, storing the binary result through pointer addrptr.
inet _ntop: Reverse conversion, from numeric (addrptr) to presentation (strptr)
Len size of destination, to prevent the function over flowing caller’s buffer.
in_addr {} in6_addr {} in6_addr {}
32-bit binary 128-bit binary 128-bit binary
IPV4 address IPV4_mapped or IPV6 address
numeric compatible IPV6 address
inet_pton (AF_INET) inet_pton (AF_INET6) inet_pton (AF_INET6)
inet_aton, inet_addr
1
inet_ntop (AF_INET) inet_ntop (AF_INET6) inet_ntop (AF_INET6)
inet_ntoa
dotted-decimal x.x.x.x.x.x.a.b.c.d x.x.x.x.x.x.x.x IPV4 address
Presentation
Fig 1.10 Summary of address conversion functions
1.7 ELEMENTRAY TCP SOCKETS Elementary TCP sockets functions are required to write a complete TCP client and server.
Elementary TCP sockets are
1. Socket function 2. Connect function 3. Bind function 4. Listen function
5.Accept function 6.Read / Write function 7. Close function
TCP SERVER
Well known port
TCP CLIENT
Connection establishment Blocks until connection from client
Data (request)
Data reply
End of file notification
Fig: 1.11 Socket functions for elementary TCP client/Server
7.1 Socket Function
To perform I/O, first the process must call the socket function along with the type of communication
protocol. Eg. TCPIPV4, UDPIPV6,Unix domain stream protocol
Syntax:
socket()
bind()
listen()
accept()
write()
read()
close()
read()
socket()
write()
read()
connect()
close()
1
#include <sys / socket .h>
int socket (int family, int type, int protocol);
Returns: No negative descriptor if ok, -1 on error
Family specifies the protocol family
Family Description AF-INET IPV4 protocolsAF-INET6 IPV6 protocolsAF-LOCAL Unix domain protocolsAF-ROUTE Routing sockets AF-KEY Key socket
Socket type is a constant
Type DescriptionSOCK-STREAM Stream SocketSOCK-DGRAM Datagram SocketSOCK-RAW Raw Socket
Protocol argument to the socket function set to o except for raw sockets.
Not all combinations of socket family valid. Valid combinations along with actual protocol are
selected by the pair. Box marked “Yes” are valid, empty boxes are not supported.
Combinations of family & type for socket function
AF-INET AF-INET6 AF-LOCAL AF-ROUTE AF-KEY
SOCK_STREAM TCP TCP YES
SOCK_ DGRAM UDP UDP YES
SOCK_RAW IPV4 IPV6 YES YES
On success the socket fn returns a small non negative integer value similar to file descriptor (fd),
called a socket file descriptor (sockfd)
1.7.1.1 AF –xxx Vs PF-xxx
1. AFPrefix address family
2. PFprefix protocol family
Single protocol family can support multiple address family. PF_value used to create Socket and
AF_value used to create Socket Address structure.
1
1.7.2 CONNECT FUNCTION
Used by the TCP client to establish a connection with a TCP server. Syntax
#include <sys / socket.h>
int connect (int sockfd, const struct sockaddr *servaddr, socklen_t
addrlen);
Returns : 0 if OK, -1 on error.
Sockfdsocket fd returned by socket function
Second and third argument ptr to the SAS and its size.
SAS must contain IP address and port number of the server. Client should not bind before calling
connect. The kernel will choose both an ephemeral port and the source IP address if needed. In the case of a
TCP socket, the connect function initiates TCP’s 3 way hand shake method and returns when connection
established or error occurs. Different error returns are possible.
1. If the TCP client receives no response to its SYN segment, waits for 75 seconds,
then ETIMEOUT error is returned.
2. If the server’s response to client’s SYN is RST that indicates no process is
waiting for connections of the server host at the port specified, called as hard
error, and ECONNREFUSED is returned to the client as soon RST is received.
RST Reset type. TCP segment that is sent by TCP when something is wrong.
Three conditions that generate RST.
a. SYN arrives for a port that has no listening server.
b. TCP wants to abort an existing connection.
c. TCP receives a segment for a connection that does not exist.
3. If the client’s SYN elicit an ICMP destination unreachable from some intermediate route called soft
error. The client kernel saves the message but keeps sending SYNs with the same time between each SYN,
if no response is received after some fixed time, the saved ICMP errors returned to the process as
either EHOSTUNREACH or ENETURREACH.
Examples for different error conditionsa. Solaris % daytimetcpcli 127.00.1 local host
i. Tue Jan 16 16.45.07 2009.
b. Solaris % daytimetcpcli 206.62.226.55
connect error : connection timed out.
1.7.3 BIND FUNCTION
1
Assigns local protocol address to a socket. With the IP, the protocol address is the combination of either
32bit IPV4 or 128 bit IPV6 address, along with 16 bit TCP or UDP port number.
Syntax
#include<sys/socket.h>
int bind(int sockfd,const struct sockaddr *myaddr,socklen_t_addrlen);
Returns: 0 if ok,-1 on error
Second argument pointer to the protocol specific address Third argumentsize of address structure
With TCP, calling bind allows to specify port number, IP address both or neither. 1. Server binds their well known port when they start. If TCP client/server doesn’t do this, kernel chooses
an ephemeral port. 2.A process can bind specific IP address to its socket, IP address much belongs to interface on host.
Table: Results when specifying IP address and / or port number to bind.
Process specifies Result
IP address port
Wildcard 0 Kernel chooses IP address and port
Wildcard Non zero Kernel chooses IP address, Process specified port.
Local IP 0 Process specified IP address, Kernel address chooses port.
Local IP addr Non zero Process specified IP address and port
If we specify port number 0, kernel chooses ephemeral port when bind function called. If we specify
wild card IP address, the kernel doesn’t choose the local address until either the socket is connected (TCP) or
until a datagram is sent on the socket (UDP). IPV4 wild card address specified by constant INADDR_ANY,
value set to 0, tells the kernel to choose IP address.
struct sockaddr_in servaddr;
servaddr.sin_addr s_addr = htonl (INADDR –ANY);
/*Wild card*/
For IPV6
struct sockaddr_in6 servaddr;
1
serv.sin6_addr = in6_any;
/*Wild card*/
The value of INADDR –ANY (0) same in either network or host byte order.
getsockname obtain value of ephemeral port assigned by the kernel to return protocol address.
1.7.4 LISTEN FUNCTION
Listen function is called only by TCP server and performs 2 actions. 1. Converts an unconnected socket (sockfd) into a passive socket.
2. Specified the maximum number of connections (backlog) that the kernel should
queue for this socket.
#include <sys /socket. h>
int listen (int sockfd, int backlog);
Returns: 0 if OK – 1 on error.
Listen function is normally called after the socket and bind functions and before accept function.
For listening socket, the kernel maintains 2 queues.
1. Incomplete queues.
2. Complete queues.
Incomplete connection queues sumof both queues cannot exceed backlog
accept
Contains entry for each SYN that has arrived from a client for which server is awaiting completion of the TCP 3
way hand shake. These sockets are in SYN – RCVD state.
Fig: 1.12 TCP 3 way handshake and 2 queues for listening socket. Complete connection queues
3 way hand shake Method Complete
Server
TCP
1
Contains entry for each client with whom the TCP 3 way handshake has completed. These sockets
are in ESTABLISHED state.
Packets exchanges during the connection establishment between 2 queues.
a. When as SYN arrives from client, TCP creates a new entry on the incomplete queues and
then responds with the second segment of 3 way handshake method. This only will remain on
the incomplete queues until the third segment of the 3 way handshake or until the entry time
outs.
b. It the 3 way handshake completes normally, the entry moves from the incomplete queues to
the end of the completed queues.
Some things to be considered while handling queues1. The backlog argument specifies the maximum value for the sum of both queues.
2. Don’t specify backlog as o.
3. Sample code always shows a backlog of 5.
4. Complete queues have more entries than incomplete queues.
5. If the queues are full, when a client SYN arrives, TCP ignores the arriving SYN, it does not send an
RST, because condition is considered temporary, client TCP will retransmit its SYN, finings room for
queues is near future.
1.7.5. ACCEPT FUNCTIONIt is called by TCP server to return the next completed connection from the front of the completed
connection queues. If the completed queues are empty, the process is put to sleep.
Syntax
# include <sys / socket. h>
int accept (int sockfd, struct sockaddr *cliaddr , socklen_t *addrlen);
Returns: non negative descriptor if ok, – 1 or error.
cliaddr, addrlen returns the protocol address of the connected peer process(client)
addrlen value result argument.
If accept successful, it returns new descriptor that was automatically created by the kernel and refers to
the TCP connection with the client.Two sockets available
1. Listening socket. 2. Connected socket.Listening socket
Served creates only one listening socket, exists for the lifetime of the server.
Connected socket
1
Kernel creates one connected socket for each client connection that is accepted, when the server finishes
serving given client, it is closed.
1.7.6 READ AND WRITE FUNCTIONS
Data can be send or received with read ( ) and write ( )
Syntax:-
write (s, buf, size of buf);
read ( s, buf, size of buf);
else send ( ) & recv() can be used Syntax :-
send (s, buf, size of buf, flags);
recv (s, buf, size of buf, flags);
send ( ) and recv() are very similar to read ( ) and write ( ), but flags argument is important. Flags are
defined in <SYS / SOCKET .h > can be specified as non zero value if one or more of the following is
required.
a. MSG_OOB send & receive out-of-bound data.b. MSG _PEEK Look at data without reading.c. MSG_ DONTROUTE sends data without routing pockets.
Out_of _bound data is specified to stream sockets.
When MSG_PEEK is specified with a recv() call, any data present is returned to the user but
treated as still unread.
Data send without routing applied to the outgoing packets is currently used only by the
routing table management process.
1.7.10 CLOSE FUNCTION UNIX close function is used to close a socket and terminate TCP connection.
Syntax:
#include<unistd.h.>int close (int sockfd);
Returns: 0 if OK – 1 on error.
The default action of close is to mark socket as closed and return to process immediately. The socket
descriptor is no longer usable by process (i.e.) can’t used as argument to read or write. But TCP will try to
send any data that is already queued to send to other end, after this termination takes place.
1.7.7 FORK AND EXEC FUNCTIONS
1
Fork function is used to create a new process
Syntax
#include <unistd.h>
pid_t fork (void);
Returns: 0 in child, process ID of the child in parent
-1 on error.
It is called once, returns twice i.e. returns once in calling process with a return value i.e. process
ID of the newly created process (child), and returns once in child with return value of 0.Hence the return
value tells the process whether it is the parent or the child. Child has only one parent and can obtain
parent’s process ID by calling getpid. Parent can have any number of children and there is no way to
obtain the process ID’s of its children.
Uses of fork:- 1. A process makes a copy of itself so that one copy can handle operations, while the other copy
does another task. Eg. Network servers.
2.A process wants to execute another program; the only way to create a new process is calling fork, and
the process first calls fork to make a copy of itself and then one of the copies calls exec to replace itself with
the new program.
Exec functions:- The only way in which an executable program file on disk is executed by UNIX is for an existing process
to call one of the six exec function. Exec replaces the current process image with new program file and this
new program normally starts at main function.
Exec function:- # include<unistd.h>
int execl (const char *pathname ,const char * argo, ….. / * (char *) 0 * /
int execv (const char *pathname , char * const argv[ ] )
int execle (const char *pathname, const char * arg0,….. /* (char*) 0 * char envp[]*/);
int execve (const char *pathname, const char * argv[],char const envp[]
int execlp (const char *filename, const char * arg0,….. /* (char*) 0 */);
int execvp (const char * filename,const char * argv [] );
All six return : -1 on error, no return on success.
The relationships among these six functions are
a. Whether the program file to execute is specified by file name or path name.
b. Whether the argument to the new program are listed one by one or referenced through an array of
pointers.
1
c. Whether the environment of the calling process is passed to the new program or whether a new
environment is specified.
1.7.8. ITERATIVE SERVER
Iterative server iterates through each client one at a time.
Example: Daytime server that prints client IP address and port.
1. #include “unp.h”2. # include <time .h.>3. int 4. main (int argc, char ** argv)5. {6. int listendfd, connfd;7. socketlen_t len;8. struct sockaddr_in servaddr, cliaddr;9. char buff [MAXLINE];10. time_t ticks;11. listenfd = Socket (AF_INET _STREAM, 0);12. bzero (&servaddr, sizeof (servaddr));13. servaddr.sin_family= AF_INET;14. servaddr.sin _addr.s_addr=htonl(INADDR-ANY);15. servaddr.sin_port=htons(13);16. Bind(listenfd,(SA*) & servaddr, sizeof(servaddr));17. listen(listendfd, LISTENQ);18. for(;;){19. len = sizeof(cliaddr);20. connfd=Accept (listenfd, (SA*) & cliaddr, & len);21. printf (“connection from %s, port %d\n”,22. inet –ntop (AF-INET, & cliaddr.sin _addr, buff,sizeof(buff),23. ntohs (clientaddr.sin_port) );24. ticks = time (NULL);25. snprint(buff,sizeof(buff),”%.24s\r\n”,ctime (&ticks));26. write (connfd,buff,strlen(buff));27. close (connfd);28. }29. }
If we run the client as
% client 206.62.226.36 8888 1 5000 4000
To an iterative server, we get the same number of TCP connections and the same amount of data transferred
across each connection. But since the server is iterative, there is no process control whatsoever performed
by the server.
Explanation:
1. Len value result variable
1
2. Cliaddr contain client’s protocol address
Lines 19 – 23: For accepting connection & printing client’s address.
inet_ntop convert 32 bit IP address in socket address structure into dotted decimal ASCII string.
ntohs convert 16 bits port number from network byte order to host byte order.
1.7.9 CONCURRENT SERVERS
It handles multiple clients at the same time. When a connection is established, accept returns,
server calls fork and then child process services the client and the parent process waits for another
connection. The parent closes the connected socket since child handles new client.
Example
pid_t pid;
int listenfd,connfd;
listenfd=socket(…);
bind(listenfd, …);
listen(listenfd,LISTENQ);
for(;;){
connfd=Accept(listenfd,….); /*probably blocker*/
if((pid=Fork())==0){
close(listenfd); /*child closes listening socket*/
doit(connfd); /*process the request*/
close(connfd); /*done with this client*/
exit(0); /*child terminates*/
}
close(connfd); /*parent closes connected socket*/
Explanation: Doit function does whatever is required to service the client. When this function returns, connected
socket is closed in client.
After socket returns, the file table associated with listenfd has a reference count 1.
After accept returns, the file table associated with connfd has a reference count 1
After fork returns, both descriptors are shared between parent and child, the file table associated with
both sockets has a reference count 2
When the parent closes connfd, it decrements the reference count from 2 to 1.
1
A real close takes place, when reference count reaches 0.
Later child closes connfd, reference count decrease to 0 and close takes place. The above explained
concepts are explained in the diagram below
Server
Client
Fig: 1.13 Status of client-server before call to accept.
Connection
Fig: 1.14 Status of client-server after return from accept.
Server (parent)
Client
Fig: 1.15 Status of client-server after fork returns
Server child
client
Server child
Listenfd
Connect ()
ListenfdConnfd
Connect ()
ListenfdConnfd
Connect ()
Listenfdconnfd
Listenfd
Connect ()
connfd
1
Fig: 1.16 Status of client-server after parent and child close appropriate sockets
2 Marks Questions and Answers1. Compare TCP and UDP
TCP(Transmission Control Protocol) UDP(User Datagram Protocol)
Connection oriented protocol. Connectionless protocol.
TCP is sophisticated reliable byte
stream protocol
UDP is simple unreliable data gram
protocol.
.
2. What is the use of ARP and RARP? ARP ( Address Resolution Protocol)
It is used to find the physical address if the IP address is known.
RARP (Reverse Address Resolution Protocol)
It is used to find the IP address if the physical address is known.
3. What is IANA?
Internet Assigned Number Authority. IANA divides the port address.
4. What is mean by well known port?
In well known port, port no and the port address are 16 bits. The range is from 0 to 1023. It is
assigned and controlled by IANA. It is used in server process.
5. Compare physical, logical and port address.
PHYSICAL LOGICAL PORT
It belongs to data link
layer. The size and the
format depends upon the
network
It belongs to network layer. This
is a 32 bit address and is uniquely
identified between the node and
internet.
It belongs to transport
layer. This is a 16 bit
address.
6. Write a program to print its own process ID.
# include<stdio.h>
#include<stdio.h>
int main(void)
{ pid_ t pid;
pid getpid();
1
printf(“My pid %d “,pid);
}
7. Write a program to print the process ID of parent and child.
#include<stdlib.h>
#include<stdio.h>
int main (void)
{ pid_t pid;
pid=fork();
if(pid ==0)
printf(“Child pid = %d\n”,pid);
pid = getppid();
printf(“My parent pid =%d\n”,pid);
return 0; }
8. Define socket. Give structure of socket.
In client server model two application programs one running on local system
(client) and another running on remote system (server) need to communicate with
one another. The communication needed in socket programming is socket
9. Define the types of socket
Stream socket (SOCK_STREAM)
Datagram socket (SOCK_DGRAM)
Raw socket (SOCK_RAW)
10. List the fields present in sockaddr_ in structure
struct sockaddr_in{unit8_t sin_len; /* length of the socket*/sa-family-t sin-family; /*AF_INET*/in-port-t sin-port; /*16 bit port addr*/struct ion-addr sin-addr; /* 32 bit IPV4 addr*/char sin-zero(8) /* unused field*/} struct In-addr{ in_addr_t s_addrt;}
struct sockaddr – in{units –t sin-len;
};
1
11. List the data types used in client server program
DATA TYPE DESCRIPTION HEADERint8_t signed 8-bit integer <sys/types,h>
unint8_t unsigned 8-bit integer <sys/types,h>
int 16_t Signed 16- bit integer <sys/types,h>
uint 16_ t Unsigned 16 -bit integer <sys/types,h>
int32_t signed 32 bit- integer <sys/types,h>
uint 32_t Unsigned 32- bit integer <sys/types
sa_family_t Address family of socket
address structure
<sys/socket.h>
socklen_t Length of the socket
address structure
<sys/socket.h>
in_addr_t IPV4 address <sys/socket.h>
In_port_t TCP or UDP port <sys/socket.h>
12. Specify the fields in sockaddr_in6 struct in6_addr{
unit8_t s6_addr[16]; /*128-bit IPV6 address */ }; /*network byte order*/
#define SIN6_LEN struct sockaddr_in6{
unit8_t sin6_len; /*length of this struct (28)*/sa_family_t sin6_family; /*AF_INET6*/int_port_t sin6_port; /*transport layer port#*/
/*network byte ordered*/ unit32_t sin6_flowinfo; /*flow information, undefined*/
struct in6_addr sin6_addr; /*IPV6 address*//*network byte ordered*/
unit32_t sin6_scope_id; /*set of interfaces for a scope*/};
13. What is network byte order?
Network byte order chooses its own byte integer by the protocols used. It may either LEBO (Little
Endian Byte Order) or BEBO (Big Endian Byte Order)
14. What is host byte order?
The byte ordering followed by a given system can be in two ways: LEBO
(Little Endian Byte Order) or BEBO (Big Endian Byte Order).this is called as
1
host byte order
15. What is the purpose of inet_aton function?
It is used to convert the dotted decimal format to 32 bit binary format in
network byte order
Syntax:
int inet_aton (const char *strptr, struct inaddr * addrptr);
Returns: 1 if string valid, 0 on error
16. What are the functions designed for byte order transformation?
There are four functions designed for byte order transformation. They are
# include <netinet/in.h>
unit16_t htons (unit 16-t host 16bitvalue);
unit32_t hton1(unit32-t host 32bitvalue);
Both return: value in network byte order
unit16_t ntohs (unit16_t net16bitvalue);
unit32_t ntohl(unit32_t32bitvalue);
Both return: value in host byte order
17. How is socket uniquely identified? The socket function returns a small non negative integer value, similar to file descriptor; we call this as
socket descriptor
Syntax: int socket (int family, int type, int protocol);
18. What is the purpose of bind and connect?
Bind: used to assign the local socket address to already connected socket
Syntax: int bind (int sockfd, const struct sockaddr *myaddr, socklen_t_addrlen);
Returns: 0 if ok,-1 on error
Connect: used by TCP client to establish active connection with TCP server
Syntax: int connect (int sockfd, const struct sockaddr * serv addr, socklen _t addrlen);
Returns: 0 if OK, -1 on error.
19. What is the need for listen and accept system calls?
Listen: enforces OS that the server is ready to accept the connection through the socket
Syntax: int listen (int sockfd, into backlog);
Returns: 0 if OK – 1 on error.
Accept: Called by TCP server to return the next completed connection from the
1
front of the completed connection queue.
Syntax:int accept (int sockfd, struct sockaddr * cliaddr socklen_ t * addrlen);
Returns: non negative descriptor if ok, – 1 on error.
20. Specify the address conversion functions
There are five address conversion functions are available.
int inet-aton (const char *strptr, sturct inaddr * addrptr);
Returns: 1 if string valid, 0 on error
in_addr_t inet_addr (const char * strptr);
Returns: 32 bit binary network byte ordered IPV4 address;
INADDR_NONE if error
char * inet_ntoa (struct in_addr inadds);
Returns: pointer to dotted-decimal string
int inet –pton (int family, const char * strptr, void * addrptr);
Returns: 1 if OK, 0 if input not a valid presentation format,
- 1 on error
const char *inet_ntop (int family, const void *addrptr, char *strptr, size_t
len);
Returns: pointer to result if OK, NULL on error.
21. Explain the operation of fork () system call
Fork () causes the process to split into two identical process, one retains the original process
identification number (PID) and is called as parent. The other called child gets a new PID
22. What are the byte manipulation operations? There are two groups of functions are for byte manipulation b(byte)
a. bzero c. bcopy
b. bcmp
mem(memory)
a. memset c.memcopy
b. memcmp
23. What is socket abstraction?
Socket is an abstraction through which an application may send and receive data, in the same way open
file allows application to read and write data to stable storage
24. Compare various socket address structure
1
IPV4SOCKADDR_in{}
IPV6SOCKADDR_in6{}
UNIX SOCKADDR_UN{}
DATALINK SOCKADDR_DL{}
Length|AF_INET Length|AF_INET6 Length|AF_LOCAL Length|AF_LINK
16 bit port# 16 bit port#
32 bit IPV4 addr 128bit IPV6 addr Type|namelenAddrlen|selen
Unused 8 bytes 32 bit Flow Label Pathname(upto 104 bytes)
Interface indexInterface name and link layer addr
25. Write short notes on sendto and recvfrom system call
Sendto: Used by UPD process to send a message to another process running on
remote machine
Syntax :ssize_t sendto(int sockfd,const void *buf,size_t buflen,int flags,const struct
sockaddr *to addr,socklen_t toaddrlen);
RECVFROM: Used by UDP process to send a reply to the sender
Syntax: ssize_t recvfrom (int sockfd, const void *buf, size_t buflen, int flags, const
struct sockaddr *fromaddr,socklen_t fromaddrlen);
26. Differentiate iterative and concurrent server
Iterative server Concurrent server
The server run’s only one client The server run’s two or more clients at
at a time same time the same time
27. What is passive and active open?
Passive Open: The server prepares to accept an incoming connection by calling socket bind and listen
function. This is called as passive open
Active open: The client connects to the server by calling the connect function. It cause the client to
sent a SYN segment .This is called as active open
28. List the services provided by TCP
a. Connection between client and server b. Reliability
c. Flow control d. Sequencing
e. Full-duplex communication
29. What is active and passive close?
1
The client/server that receives the FIN segment from the other end performs the passive close. The
client/server which calls the close function first is performing active close.
30. What is half-close?
The dataflow from the end doing the passive close to the end doing the active open is called as half-close
16 MARKS QUESTIONS 1. Explain in detail about TCP/IP protocols
2. i)Compare physical, logical and port address
ii)Explain byte manipulation functions
3. i)What are the data types used in client-server programs
ii) What is the purpose of inet_addr and inet_pton functions?
4. i) What is socket abstraction? Explain
ii) Compare various address structures
5. i) How a socket is uniquely identified?
ii) Explain the address conversion functions
6. Explain the following system calls
a. Write c. Read
b. Recvfrom d.Listen
7.Explain the following system calls
a. connect c.sendto
b. accept d.bind8. Explain the required socket functions for implementing a UDP client/server application
9. Write a socket program to implement TCP client-server
10. Write short notes on
a. Iterative server b. Concurrent server c. fork()