1 SUB: IT1352 -NETWORK PROGRAMMING AND MANAGEMENT UNIT I ELEMENTARY 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.
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
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.
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
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
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