DECCAN COLLEGE OF ENGINEERING & TECHNOLOGY
Transcript of DECCAN COLLEGE OF ENGINEERING & TECHNOLOGY
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 1
DECCAN COLLEGE OF ENGINEERING & TECHNOLOGY Dar-us-Salam, Hyderabad -500 001.
DEPARTMENT OF INFORMATION TECHNOLOGY
COMPUTER NETWORKS LAB MANUAL 2021
Prepared by Ms Reshma Begum
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 2
DECCAN COLLEGE OF ENGINEERING & TECHNOLOGY
Dar-us-Salam, Hyderabad -500 001.
INDEX
S.No. Program
1 Familiarization of Network Environment, Understanding and using network
utilities: ipconig, ifconfig, netstat, ping, arp, telnet,ftp,finger,traceroute.
2 Write a program to implement connection oriented and connectionless client for well known
services i.e standard ports
3 Implementation of concurrent server service using connection oriented socket system
calls(Service: Daytime, Time)
4 Implementation of concurrent server using connection less socket system calls. (Service:
Echo server)
5 Implementation of Iterative server using connection oriented socket system
calls.(Service:Calculate Employee Salary)
6 Implementation of Iterative server using connection less socket system calls. (Service:
Student Grade)
7 Program to demonstrate the use of advanced socket sytem calls : readv(),writev()
getsockname(),setsockname(),getpeername().
8 Implementation of remote command execution using socket system calls.
9 Program to implement simple program using RPC.
10 Implementation of Distance Vector Routing Protocol.
11 Implementation of RSA public key algorithm
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 3
Lab Course Objectives:
To understand the use of client/server architecture in application development.
➢ To understand and use elementary socket system calls, advanced socket system calls and
➢ TCP and UDP based sockets
➢ To implement network routing algorithms, application layer protocols and encryption
algorithms.
Lab Course Outcomes:
Student will be able to
➢ Understand the usage of basic commands ipconig, ifconfig, netstat, ping, arp,
telnet,ftp,finger,traceroute, whois of LINUX platform.
➢ Develop and Implement Client-Server Socket based programs using TCP,and UDP
sockets
➢ Develop and Implement Distance Vector Routing Algorithm
➢ Develop and Implement RSA Public Key algorithm
➢ Construct simple network by using any modern Open Source Network Simulation
Tool.
Software requirements Operating system: Linux/Ubuntu
Language : C
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 4
I.INTRODUCTION
The Windows Sockets Specification has been built upon the Berkeley Sockets programming
model which is the de facto standard for TCP/IP networking. It is intended to provide a high
degree of familiarity for programmers who are used to programming with sockets in UNIX and
other environments, and to simplify the task of porting existing sockets-based source code. The
Windows Sockets API is consistent with release 4.3 of the Berkeley Software Distribution
(4.3BSD).
What is a network?
What usually call a computer network is composed of a number of "network layers”, each
providing a different restriction and/or guarantee about the data at that layer. The protocols at
each network layer generally have their own packet formats, and headers.
The seven traditional layers of a network are divided into two groups: upper layers and lower
layers. The sockets interface provides a uniform API to lower layers of a network, and allows
implementing upper layers within r sockets application. Further, application data formats may
themselves constitute further layers, e.g. SOAP is built on top of XML, and XML may itself
utilize SOAP.
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 5
What is a socket?
While the sockets interface theoretically allows access to protocol families other than IP,
in practice, every network layer use in r sockets application will use IP. At the transport layer, sockets
support two specific protocols: TCP (transmission control protocol) and UDP (user datagram
protocol). Sockets cannot be used to access lower (or higher) network layers; for example, a socket
application does not know whether it is running over ethernet, token ring, or a dialup connection.
Nor does the sockets pseudo-layer know anything about higher-level protocols like NFS, HTTP, FTP
At times, the sockets interface is not r best choice for a network programming API. Specifically,
many excellent libraries exist (in various languages) to use higher- level protocols directly, without
having to worry about the details of sockets--the libraries handle those details. Lower-level layers
than those sockets address fall pretty much in the domain of device driver programming.
➢ The basic building block for communication is the socket. A socket is an endpoint of
communication to which a name may be bound. Each socket in use has a type and an associated
process. Sockets exist within communication domains. A communication domain is an
abstraction introduced to bundle common properties of threads communicating through sockets.
Sockets normally exchange data only with sockets in the same domain (it may be possible to
cross domain boundaries, but only if some translation process is performed). The Windows
Sockets facilities support a single communication domain: the Internet domain, which is used by
processes which communicate using the Internet Protocol Suite. (Future versions of this
specification may include additional domains.)
➢ Sockets are typed according to the communication properties visible to a user. Applications
are presumed to communicate only between sockets of the same type, although there is nothing
that prevents communication between sockets of different types should the underlying
communication protocols support.
➢ Two types of sockets currently are available to a user. A stream socket provides for the bi-
directional, reliable, sequenced, and unduplicated flow of data without record boundaries.
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 6
➢ A datagram socket supports bi-directional flow of data which is not promised to be
sequenced, reliable, or unduplicated. That is, a process receiving messages on a datagram socket
may find messages duplicated, and, possibly, in an order different from the order in which it was
sent. An important characteristic of a datagram socket is that record boundaries in data are
preserved. Datagram sockets closely model the facilities found in many contemporary packet
switched networks such as Ethernet.
IP, TCP and UDP
As the last panel indicated, when program a sockets application, have a choice to make
between using TCP and using UDP. Each has its own benefits and disadvantages.
➢ TCP is a stream protocol, while UDP is a datagram protocol. TCP establishes a continuous
open connection between a client and a server, over which bytes may be written-- and correct
order guaranteed--for the life of the connection. Hover, bytes written over TCP have no built-in
structure, so higher-level protocols are required to delimit any data records and fields within the
transmitted byte stream.
➢ UDP, on the other hand, does not require that any connection be established between client
and server; it simply transmits a message between addresses. A nice feature of UDP is that its
packets are self-delimiting--each datagram indicates exactly where it begins and ends. A possible
disadvantage of UDP, hover, is that it provides no guarantee that packets will arrive in-order, or
even at all. Higher-level protocols built on top of UDP may, of course, provide handshaking and
acknowledgements.
➢ A useful analogy for understanding the difference between TCP and UDP is the difference
between a telephone call and posted letters. The telephone call is not active until the caller "rings"
the receiver and the receiver picks up. The telephone channel remains alive as long as the parties
stay on the call--but they are free to say as much or as little as they wish to during the call. All
remarks from either party occur in temporal order. On the other hand, when send a letter, the post
office starts delivery without any assurance the recipient exists, nor any strong guarantee about
how long delivery will take. The recipient may receive various letters in a different order than
they re sent, and the sender may receive mail interspersed in time with
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 7
those she sends. Unlike with the USPS, undeliverable mail always goes to the dead letter office,
and is not returned to sender.
Peers, ports, names, and addresses
Beyond the protocol--TCP or UDP--there are two things a peer (a client or server) needs
to know about the machine it communicates with: An IP address and a port. An IP address is a
32-bit data value, usually represented for humans in "dotted quad" notation, e.g., 64.41.64.172.
A port is a 16-bit data value, usually simply represented as a number less than 65536--most often
one in the tens or hundreds range. An IP address gets a packet to a machine, a port lets the
machine decide which process/service (if any) to direct it to. That is a slight simplification, but
the idea is correct.
The above description is almost right, but it misses something. Most of the time when humans
think about an internet host (peer), do not remember a number like 64.41.64.172, but instead a
name like gnosis.cx.
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 8
II. ABOUT SYNTAX
Most network applications can be divided into two pieces: a client and a server.
Creating a socket
#include <sys/types.h>
#include <sys/socket.h>
When you create a socket there are three main parameters that you have to specify:
• the domain
• the type
• the protocol
int socket(int domain, int type, int protocol);
DESCRIPTION
Socket creates an endpoint for communication and returns a descriptor. The domain parameter
specifies a communication domain this selects the protocol family which will be used for
communication. These families are defined in <sys/socket.h>. The currently understood formats
include:
Name Purpose
PF_UNIX,PF_LOCAL Local communication
PF_INET IPv4 Internet protocols
PF_INET6 IPv6 Internet protocols
PF_IPX IPX - Novell protocols
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 9
The socket has the indicated type, which specifies the communication semantics. Currently
defined types are:
SOCK_STREAM:
Provides sequenced, reliable, two-way, connection- based byte streams. An out-of-band data
transmission mechanism may be supported.
SOCK_DGRAM:
Supports datagrams (connectionless, unreliable messages of a fixed maximum length).
SOCK_SEQPACKET:
Provides a sequenced, reliable, two-way connection- based data transmission path for datagrams
of fixed maximum length; a consumer is required to read an entire packet with each read system
call.
SOCK_RAW:
Provides raw network protocol access.
SOCK_RDM:
Provides a reliable datagram layer that does not guarantee ordering.
SOCK_PACKET:
Obsolete and should not be used in new programs. Some socket types may not be implemented by
all protocol families. For example, SOCK_SEQPACKET is not implemented for AF_INET.
The protocol specifies a particular protocol to be used with the socket. Normally only a single
protocol exists to support a particular socket type within a given protocol family. However, it is
possible that many protocols may exist, in which case a particular protocol must be specified in
this manner. The protocol number to use is specific to the "communication domain" in which
communication is to take place.
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 10
Sockets of type SOCK_STREAM are full-duplex byte streams, similar to pipes. They do not
preserve record boundaries. A stream socket must be in a connected state before any data may be
sent or received on it. A connection to another socket is created with a connect call. Once
connected, data may be transferred using read and write calls or some variant of the send and recv
calls. When a session has been completed a close may be performed. Out-of-band data may also
be transmitted as described in send and received as described in recv.
The communications protocols which implement a SOCK_STREAM ensure that data is not lost
or duplicated. If a piece of data for which the peer protocol has buffer space cannot be successfully
transmitted within a reasonable length of time, then the connection is considered to be dead. When
SO_KEEPALIVE is enabled on the socket the protocol checks in a protocol- specific manner if
the other end is still alive. A SIGPIPE signal is raised if a process sends or receives on a broken
stream; this causes naive processes, which do not handle the signal, to exit. SOCK_SEQPACKET
sockets employ the same system calls as SOCK_STREAM sockets. The only difference is that
read calls will return only the amount of data requested, and any remaining in the arriving packet
will be discarded. Also all message boundaries in incoming datagrams are preserved.
SOCK_DGRAM and SOCK_RAW sockets allow sending of datagrams to correspondents named
in send calls. Datagrams are generally received with recvfrom, which returns the next datagram
with its return address.
SOCK_PACKET is an obsolete socket type to receive raw packets directly from the device driver.
Use packet instead. When the network signals an error condition to the protocol module (e.g. using
a ICMP message for IP) the pending error flag is set for the socket. The next operation on this
socket will return the error code of the pending error. For some protocols it is possible to enable a
per-socket error queue to retrieve detailed information about the error; see IP_RECVERR in ip.
The operation of sockets is controlled by socket level options. These options are defined in
<sys/socket.h>.Setsockopt and getsockopt are used to set and getoptions, respectively.
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 11
RETURN VALUE
-1 is returned if an error occurs otherwise the return value is a descriptor referencing the socket.
EXAMPLE: The Domain parameter specifies a communications domain within which
communication will take place, in our example the domain parameter was AF_INET, that specify
the ARPA Internet Protocols The Type parameter specifies the semantics of communication, in
our mini chat we used the Stream socket type(SOCK_STREAM), because it offers a bi-directional,
reliable, two-way connection based byte stream(resource 2). Finally the protocol type, since we
used a Stream Socket type we must use a protocol that provide a connection-oriented protocol, like
IP, so we decide to use IP in our protocol Type, and we saw in
/etc/protocols the number of ip, 0. So our function now is:
s = socket(AF_INET , SOCK_STREAM , 0)
where 's' is the file descriptor returned by the socket function.
Binding a socket to a port and waiting for the connections
Like all services in a Network TCP/IP based, the sockets are always associated with a port, like
Telnet is associated to Port 23, FTP to 21... In our Server we have to do the same thing, bind some
port to be prepared to listening for connections (that is the basic difference between Client and
Server), Listing 2. Bind is used to specify for a socket the protocol port number where it will be
waiting for messages. So there is a question, which port could we bind to our new service? Since
the system pre-defined a lot of ports between 1 and 7000 ( /etc/services ) we choose the port
number 15000.
BIND:
Bind will bind a name to socket, it gives the socket sockfd, the local address myaddr, myaddr is
addrlen bytes long.Traditionally, this is called assigning a name to a socket. When a socket is
created with sockect () it exists in a name space but has no name assigned. It is normally necessary
to assign local address using bind before sock_stream socket may receive connection.
int bind(int sockfd,const struct sockaddr *myaddr,socklen_t addrlen);
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 12
The struct necessary to make socket works is the struct sockaddr_in address; and then we have
the follow lines to say to system the information about the socket.
The type of socket
address.sin_family = AF_INET /* use a internet domain */
The IP used
address.sin_addr.s_addr = INADDR_ANY /*use a specific IP of host*/
The port used
address.sin_port = htons(15000); /* use a specific port number */
And finally bind our port to the socket
bind(create_socket , (struct sockaddr *)&address,sizeof(address));
Now another important phase, prepare a socket to accept messages from clients, the listen
function is used on the server in the case of connection oriented communication and also the
maximum number of pending connections
RETURN VALUE:
On sucess0 is return, on error –1 is returned and errno is set to appropriately.
LISTEN:
listen - listen for connections on a socket
#include <sys/socket.h>
int listen(int s, int backlog);
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 13
DESCRIPTION
To accept connections, a socket is first created with socket, a willingness to accept incoming
connections and a queue limit for incoming connections are specified with listen, and then the
connections are accepted with accept. The listen call applies only to sockets of type
SOCK_STREAM or SOCK_SEQPACKET. The backlog parameter defines the maximum length
the queue of pending connections may grow to. If a connection request arrives with the queue
full the client may receive an error with an indication of ECONNREFUSED or, if the underlying
protocol supports retransmission, the request may be ignored so that retries succeed.
RETURN VALUE On success, zero is returned. On error, -1 is returned, and errno is set
appropriately.
ERRORS
EADDRINUSE: Another socket is already listening on the same port.
EBADF: The argument s is not a valid descriptor.
ENOTSOCK: The argument s is not a socket.
EOPNOTSUPP: The socket is not of a type that supports the listen operation.
CONNECT: initiate a connection on a socket
The parameters are the socket descriptor of the master socket (create_socket), followed by a
sockeaddr_in structure and the size of the structure.(resource 3) Maybe the biggest difference is
that client needs a Connect() function. The connect operation is used on the client side to identify
and, possibly, start the connection to the server. The connect syntax is
#include <sys/types.h>
#include <sys/socket.h>
int connect(int sockfd, const struct sockaddr *serv_addr, sizeof(address));
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 14
DESCRIPTION
The file descriptor sockfd must refer to a socket. If the socket is of type SOCK_DGRAM then
the serv_addr address isthe address to which datagrams are sent by default, and the only address
from which datagrams are received. If the socket is of type SOCK_STREAM or
SOCK_SEQPACKET, this call attempts to make a connection to another socket. The other
socket is specified by serv_addr, which is an address (of length addrlen) in the communications
space of the socket. Each communications space interprets the serv_addr parameter in its own
way.
Generally, connection-based protocol sockets may successfully connect only once;
connectionless protocol sockets may use connect multiple times to change their association.
Connectionless sockets may dissolve the association by connecting to an address with the
sa_family member of sockaddr set to AF_UNSPEC.
RETURN VALUE
If the connection or binding succeeds, zero is returned.
On error, -1 is returned, and errno is set appropriately.
ERRORS
The following are general socket errors only. There may be other domain-specific error codes.
EBADF The file descriptor is not a valid index in the descriptor table.
EFAULT The socket structure address is outside the user's address space.
ACCEPT it accept a socket connection. And to finish we have to tell the server to accept a
connection, using the accept ( ) function. Accept is used with connection based sockets such as
streams.
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 15
#include <sys/types.h>
#include <sys/socket.h>
int accept(int s, struct sockaddr *addr, socklen_t *addrlen);
DESCRIPTION
The accept function is used with connection-based socket types (SOCK_STREAM,
SOCK_SEQPACKET and SOCK_RDM). It extracts the first connection request on the queue
of pending connections, creates a new connected socket with mostly the same properties as s,
and allocates a new file descriptor for the socket, which is returned. The newly created socket
is no longer in the listening state. The original socket s is unaffected by this call. Note that
any per file descriptor flags (everything that can be set with the F_SETFL fcntl, like non blocking
or async state) are not inherited across an accept.
The argument addr is a pointer to a sockaddr structure. This structure is filled in with the address
of the connecting entity, as known to the communications layer. The exact format of the address
passed in the addr parameters determined by the socket's family The addrlen argument is a value-
result parameter: it should initially contain the size of the structure pointed to by addr, on return
it will contain the actual length (in bytes) of the address returned. When addr is NULL nothing
is filled in.
If no pending connections are present on the queue, and the socket is not marked as non- blocking,
accept blocks the caller until a connection is present. If the socket is marked non- blocking and
no pending connections are present on the queue, accept returns EAGAIN.
In order to be notified of incoming connections on a socket, you can use select. A readable event
will be delivered when a new connection is attempted and you may then call accept to get a
socket for that connection. Alternatively, you can set the socket to deliver SIGIO when activity
occurs on a socket;
There may not always be a connection waiting after a SIGIO is delivered or select or poll return
a readability event because the connection might have been removed by an asynchronous network
error or another thread before accept is called. If this happens then the call will block
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 16
waiting for the next connection to arrive. To ensure that accept never blocks, the passed
socket s needs to have the O_NONBLOCK flag set .
RETURN VALUE
The call returns -1 on error. If it succeeds, it returns a non-negative integer that is a descriptor
for the accepted socket
RECV, RECVFROM: receive a message from a socket
#include <sys/types.h>
#include <sys/socket.h>
int recv(int s, void *buf, size_t len, int flags);
int recvfrom(int s, void *buf, size_t len, int flags
struct sockaddr *from, socklen_t *fromlen);
DESCRIPTION
The recvfrom and recvmsg calls are used to receive messages from a socket, and may be used
to receive data on socket whether or not it is connection-oriented.
If from is not NULL, and the socket is not connection-oriented, the source address of the message
is filled in the argument fromlen is a value-result parameter, initialized to the size of the buffer
associated with from, and modified on return to indicate the actual size of the address stored
there.
The recv call is normally used only on a connected socket and is identical to recvfrom with a
NULL from parameter.
All three routines return the length of the message on successful completion. If a message is too
long to fit in the supplied buffer, excess bytes may be discarded depending on the type of socket
the message is received from socket when more data arrives.
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 17
The flags argument to a recv call is formed by OR'ing one or more of the following values:
RETURN VALUE
These calls return the number of bytes received, or -1 if an error occurred.
SENDTO, SEND: send a message from a socket
#include <sys/types.h>
#include <sys/socket.h>
int send(int s, const void *msg, size_t len, int flags); int
sendto(int s, const void *msg, size_t len, int flags, const
struct sockaddr *to, socklen_t tolen);
DESCRIPTION
Send, sendto are used to transmit a message to another socket. Send may be used only when the
socket is in a connected state, while sendto may be used at any time.The address of the target is
given by to with tolen specifying its size. The length of the message is given by len. If the
message is too long to pass atomically through the underlying protocol, the error EMSGSIZE is
returned, and the message is not transmitted. No indication of failure to deliver is implicit in a
send. Locally detected errors are indicated by a return value of-1.
When the message does not fit into the send buffer of the socket, send normally blocks, unless the
socket has been placed in non-blocking I/O mode. In non-blocking mode it would return EAGAIN
in this case. The select call may be used to determine when it is possible to send more data.
RETURN VALUE
The calls return the number of characters sent, or -1 if an error occurred.
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 18
III. Design of Server Software
Servers can be classified based on
1) their servicing discipline (iterative or concurrent);
2) their communication methods (connection-oriented or connectionless);
3) their information that they keep (stateless or stateful).
Iterative Server
An iterative server serves the requests one after the other.
It is easier to design and implement.
Iterative design is suitable when the service time for eachrequest is small (because the mean response
time is stillacceptably small).
It is suitable for simple services such as the TIMEservice. Iterative design is not suitable when
the service time for arequest may be large.
Example
Two clients are using a file transfer service:
• the 1st client requests to get a file of size 200 Mbytes,
• the 2nd client requests to get a file of size 20 bytes.
If iterative design is used, the 2nd client has to wait a long time.
Concurrent Server
A concurrent server serves multiple clients simultaneously.
Concurrency refers to either
1) real simultaneous computing (using multiple processors)
2) apparent simultaneous computing (by time sharing).Concurrent design is more difficult to
implement, but it can give a smaller response time when
3) Different clients require very different service time, or the service requires significant I/O,
or the server is executed on a computer with multiple processors.
Process and Thread
We can use processes and threads to realize concurrency on a processor via time sharing.
Process
A process is a fundamental unit of computation. The OS has to store various information about
each process.
Thread
• Windows provides a second form of concurrent execution known as threads of execution or
threads.
• Each thread must be associated with a single process.
• A thread is executed independently of other threads.
• All threads in a process share: (i) global variables and (ii) resources that the OS allocates to the
process.
• Each thread in a process has its own local variables
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 19
For example, if multiple threads execute the following
piece of code,
for ( i=1 ; i<=10 ; i++ )
printf ( "%d\n" , i ) ;
then each thread has its own index variable i.
Connection-Oriented Servers
A connection-oriented server uses TCP for connection-oriented communication. TCP
provides reliable transport. The servers need not do so. The servers are simpler. A
server uses a separate socket for each connection.
Connectionless Servers
A connectionless server uses UDP for connectionlesscommunication. UDP does not guarantee
reliable transport. A connectionless server may need to realize reliabilitythrough timeout and
retransmission. The server and client are relatively complicated.
Stateless Server
A stateless server does not keep information about the
ongoing interactions with each client.
Example
• Consider the service that a client can read a file storedon the server’s computer.
• Tomaintain stateless, each client’s request must specifya file name, a position in the file, and the
number ofbytes to read.
• The server handles each request independently:
• open the specified file,
• seek to the specified position,
• read the specified number of bytes,
• send these bytes to the client,
• close the file.
Stateless servers are less efficient but they are more reliable they may be a good choice for UDP
transport.
Stateful Servers
A stateful server keeps information about the status ongoing interactions with each client.
Example
• Consider the file-reading service.
• The server maintains the following information:
• File reading can be more efficient.
Four possible types of server designs:
1. Iterative, connection-oriented server.
2. Iterative, connectionless server.
3. Concurrent, connection-oriented server.
4. Concurrent, connectionless server.
Some iterative server use tcp because to send data reliable
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 20
1. Understanding of arp, telnet, ftp, finger, traceroute, ifconfig, netstat, ping Commands
ARP
arp - manipulate the system ARP cache
arp [-evn] [-H type] [-i if] -a [hostname]
arp [-v] [-i if] -d hostname [pub]
arp [-v] [-H type] [-i if] -s hostname hw_addr [temp]
arp [-v] [-H type] [-i if] -s hostname hw_addr [netmask nm] pub
arp [-v] [-H type] [-i if] -Ds hostname ifa [netmask nm] pub
arp [-vnD] [-H type] [-i if] -f [filename]
DESCRIPTION
Arp manipulates the kernel's ARP cache in various ways. The primary options are clearing an
address mapping entry and manually setting up one. For debugging purposes, the arp program also
allows a complete dump of the ARP cache.
OPTIONS
-v, --verbose
Tell the user what is going on by being verbose.
-n, --numeric
shows numerical addresses instead of trying to determine symbolic host, port or user names.
-H type, --hw-type type, -t type
When setting or reading the ARP cache, this optional parameter tells arp which class of entries
it should check for. The default value of this parameter is ether (i.e. hardware code
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 21
0x01 for IEEE 802.3 10Mbps Ethernet). Other values might include network technologies such
as ARCnet (arc net) , PROnet (pronet) , AX.25 (ax25) and NET/ROM(netrom).
-a [hostname], --display [hostname]
Shows the entries of the specified hosts. If the hostname parameter is not used, all entries will be
displayed. The entries will be displayed in alternate (BSD) style.
-d hostname, --delete hostname
Remove any entry for the specified host. This can be used if the indicated host is brought down,
forexample.
-D, --use-device
Use the interface ifa's hardware address.
-e Shows the entries in default (Linux) style.
-i If, --device If
Select an interface. When dumping the ARP cache only entries matching the specified interface
will be printed. When setting a permanent or temp ARP entry this interface will be associated with
the entry; if this option is not used, the kernel will guess based on the routing table. For pub
entries the specified interface is the interface on which ARP requests will be answered.
NOTE: This has to be different from the interface to which the IP datagrams will be routed.
-s hostname hw_addr, --set hostname
Manually create an ARP address mapping entry forhost hostname with hardware address set to
hw_addr class, but for most classes one can assume that the usual presentation can be used. For
the Ethernet class, this is 6 bytes in hexadecimal, separated by colons. When adding proxy arp
entries (that is those with the publish flag set a netmask may be specified to proxy arp for entire
subnets. This is not good practice, but is supported by older ker nels because it can
be useful. If the temp flag is not supplied entries will be permanent stored into the ARP cache.
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 22
NOTE: As of kernel 2.2.0 it is no longer possible to set an ARP entry for an entire subnet. Linux
instead does automagic proxy arp when a route exists and it is forwarding.
-f filename, --file filename
Similar to the -s option, only this time the address info is taken from file filename set up. The
name of the data file is very often /etc/ethers, but this is not official. If no filename is specified
/etc/ethers is used as default.
The format of the file is simple; it only contains ASCII text lines with a hostname, and a hardware
address separated by whitespace. Additionally the pub, temp and netmask flags can be used.
In all places where a hostname is expected, one can also enter an IP address indotted-decimal
notation. As a special case for compatibility the order of the hostname and the hardware address
can be exchanged. Each complete entry in the ARP cache will be marked with the C flag.
Permanent entries are marked with M and published entries have the P flag.
TELNET
NAME
telnet - user interface to the TELNET protocol
telnet [-8EFKLacdfrx] [-X authtype] [-b hostalias] [-e escapechar]
[-k realm] [-l user] [-n tracefile] [host [port]]
DESCRIPTION
The telnet command is used to communicate with another host using the TELNET protocol. If
telnet is invoked without the host argument, it enters command mode, indicated by its prompt
(telnet>). In this mode, it accepts and executes the commands listed below. If it is invoked with
arguments, it performs an open command with those arguments.
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 23
The options are as follows:
-8 Specifies an 8-bit data path. This causes an attempt to negotiate the TELNET BINARY
option on both input and output.
-E Stops any character from being recognized as an escape character.
-F If Kerberos V5 authentication is being used, the -F option allows the local credentials to be
forwarded to the remote system including any credentials that have already been forwarded
into the local environment.
-K Specifies no automatic login to the remote system.
-L Specifies an 8-bit data path on output. This causes the BINARY option to be
negotiated on output.
-X atype Disables the atype type of authentication.
-a Attempt automatic login. Currently, this sends the user name via the USER variable of the
ENVIRON option if supported by the remote system. The name used is that of the current
user as returned by getlogin(2) if it agrees with the current user ID, otherwise it is the name
associated with the user ID.
-b hostalias
Uses bind(2) on the local socket to bind it to an aliased address (see ifconfig(8) and the ``alias''
specifier) or to the address of another interface than the one naturally chosen by connect(2).
This can be useful when connecting to services which use IP addresses for authentication and
reconfiguration of the server is undesirable (or impossible).
-c Disables the reading of the user's .telnetrc file.
-d Sets the initial value of the debug toggle to TRUE.
-e escapechar
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 24
Sets the initial telnet escape character to escapechar. If escapechar is omitted, then there will be no
escape character.
-f If Kerberos V5 authentication is being used, the -f option allows the local credentials to be
forwarded to the remote system.
-k realm
If Kerberos authentication is being used, the -k option requests that telnet obtain tickets for the
remote host in realm realm instead of the remote host's realm, as determined by
krb_realmofhost(3).
-l user
When connecting to the remote system, if the remote system understands the ENVIRON option,
then user will be sent to the remote system as the value for the variable USER. This option implies
the -a option. This option may also be used with the open command.
-n tracefile
Opens tracefile for recording trace information.
-r Specifies a user interface similar to rlogin(1). In this mode, the escape character is set to the
tilde (~) character, unless modified by the -e option.
-x Turns on encryption of the data stream if possible.
host Indicates the official name, an alias, or the Internet address of a remote host.
port Indicates a port number (address of an application). If a number is not specified, the default
telnet port is used. When in rlogin mode, a line of the form ~. disconnects from the remote
prompt.
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 25
FINGER
finger - user information lookup program
finger [-lmsp] [user ...] [user@host ...]
DESCRIPTION
The finger displays information about the system users.
Options are:
-s Finger displays the user's login name, real name, terminal name and write status (as a ``*''
after the terminal name if write permission is denied), idle time, login time, office location
and office phone number. Login time is displayed as month, day, hours and minutes, unless
more than six months ago, in which case the year is displayed rather than the hours and
minutes. Unknown devices as well as nonexistent idle and login times are displayed as
single asterisks.
-l Produces a multi-line format displaying all of the information
Described for the -s option as well as the user's home directory, home phone number, login shell,
mail status, and the contents of he files ``.plan'', ``.project'', ``.pgpkey'' and ``.forward'' from the
user's home directory. If write permission is denied to the device, the phrase ``(messages off)'' is
appended to the line containing the device name. One entry per user is displayed with the -l option;
if a user is logged on multiple times, terminal information is repeated once per login.
Mail status is shown as ``No Mail.'' if there is no mail at all,
``Mail last read DDD MMM ## HH:MM YYYY (TZ)'' if the person has looked at their
mailbox since new mail arriving, or ``New mail received ...'', `` Unread since ...'' if they have new
mail. -p Prevents the -l option of finger from displaying the contents of the ``.plan'',
``.project'' and ``.pgpkey'' files.
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 26
-m Prevent matching of user names. User is usually a login name; how ever, matching
will also be done on the users' real names, unless the -m option is supplied. All name matching
performed by finger is case insensitive.
If no options are specified, finger defaults to the -l style output if operands are provided, otherwise
to the -s style. Note that some fields may be missing, in either format, if information is not
available for them. If no arguments are specified, finger will print an entry for each user currently
logged into the system. Finger may be used to look up users on a remote machine. The format is
to specify a user as ``user@host'', or ``@host'', where the default output format for the former is
the -l style, and the default output format for the latter is the -s style. The -l option is the only
option that may be passed to a remote machine.
If standard output is a socket, finger will emit a carriage return (^M) before every linefeed (^J).
This is for processing remote finger requests when invoked by fingered(8).
FTP
NAME
ftp - Internet file transfer program
ftp [-pinegvd] [host]
pftp [-inegvd] [host]
DESCRIPTION
Ftp is the user interface to the Internet standard File Transfer Protocol. The program allows a user
to transfer files to and from a remote network site Options may be specified at the command line,
or to the command interpreter.
-p Use passive mode for data transfers. Allows use of ftp in environ¡ments where a firewall
prevents connections from the outside world back to the client machine. Requires that the
ftp server support the PASV command. This is the default now for all clients (ftp and pftp)
due to security concerns using the PORT transfer mode. The flag is kept for compatibility
only and has no effect anymore.
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 27
-i Turns off interactive prompting during multiple file transfers.
-n Restrains ftp from attempting ``auto-login'' upon initial connection. If auto-login is enabled,
ftp will check the .netrc (see netrc(5)) file in the user's home directory for an entry
describing an account on the remote machine. If no entry exists, ftp will prompt for the
remote machine login name (default is the user identity on the local machine), and, if
necessary, prompt for a password and an account with which to login.
-e Disables command editing and history support, if it was compiled into the ftp executable.
Otherwise, does nothing.
-g Disables file name globbing.
-v Verbose option forces ftp to show all responses from the remote
server, as well as report on data transfer statistics.
-d Enables debugging. The client host with which ftp is to communicate may be specified on
the command line. If this is done, ftp will immediately attempt to establish a connection to
an FTP server on that host; otherwise, ftp will enter its command interpreter and await
instructions from the user. When ftp is awaiting commands from the user the prompt ̀ ftp>'
is provided to the user. The following commands are recognized by ftp:
! [command [args]]
Invoke an interactive shell on the local machine. If there are arguments, the first is taken to be
command to execute directly, with the rest of the arguments as its arguments.
$ macro-name [args]
Execute the macro macro-name that was defined with the macdef command.
Arguments are passed to the macro unglobbed.
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 28
account [passwd] Supply a supplemental password required by a remote system for access to resources
once a login has been successfully completed. If no argument is included, the user will be prompted
for an account password in a non-echoing input mode.
append local-file [remote-file]
Append a local file to a file on the remote machine.If remote-file is left unspecified, the local file
name is used in naming the remote file after being altered by any ntrans or nmap setting. File
transfer uses the current settings for type, format, mode, and structure.
TRACEROUTE
The traceroute command traces the network path of Internet routers that packets take as they are
forwarded from your computer to a destination address. The "length" of the network connection is
indicated by the number of Internet routers in the traceroute path. Traceroutes can be useful to
diagnose slow network connections. For example, if you can usually reach an Internet site but it is
slow today, then a traceroute to that site should show you one or more hops with either long times
or marked with "*" indicating the time was really long. If so, the blockage could be anywhere from
your Internet service provider to a backbone provider, and there is likely little you can do except
wait with the infinite patience of the mighty oak.
The subsections below describe operating system traceroute versions, traceroute web sites, lists of
traceroute information sites, and the original version of the traceroute program.
Traceroute operating systems. On a Windows computer, you can run a traceroute in an MSDOS
or Command window by typing "tracert" followed by the domain name, for example as in "tracert
www.yahoo.com"
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 29
Like most Internet utilities, the traceroute command was originally developed for Unix
computers. The options for the original Unix traceroute command line version are
shown below:
traceroute [-m #] [-q #] [-w #] [-p #] {IP_address|host_name}
Option Definition
-m Set the maximum Time To Live (TTL) for the trace,
measured as the number of hosts the program will
trace before ending, default of 30
-q Set the number of UDP packets to send for each setting,
default of 3.
-w Set the amount of seconds to wait for an answer from each
host before giving up, default of 5
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 30
-p Specify the other host's invalid port address, default of 33434
Print the route packets take to network host.
SYNTAX
traceroute [-d] [-F] [-I] [-n] [-v] [-x] [-f first_ttl] [-g gateway [-g gateway] | -r] [-i iface] [-m
max_ttl] [-p port] [-q nqueries] [-s src_addr] [-t tos] [-w waittime ] host [packetlen]
-d Set the SO_DEBUG socket option.
-F Set the "don't fragment" bit.
-I Use ICMP ECHO instead of UDP datagrams.
-n Print hop addresses numerically rather than symbolically and numerically. This
saves a nameserver address-to-name lookup for each gateway found on
the path.
-v Verbose output. For each hop, the size and the destination of the response
packets is displayed. Also ICMP packets received other than
TIME_EXCEEDED and UNREACHABLE are listed as well.
-x Prevent traceroute from calculating checksums. Note that checksums are
usually required for the last hop when using ICMP ECHO probes. See
the -I option.
-f first_ttl Set the starting ttl value to first_ttl, to override the default value 1. traceroute
skips processing for those intermediate gateways which are less than
first_ttl hops away.
-g gateway Specify a loose source route gateway. The user can specify more than one
gateway by using -g for each gateway. The maximum that can be set is
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 31
8.
-r Bypass the normal routing tables and send directly to a host on an attached
network. If the host is not on a directly-attached network, an error is
returned. This option can be used to send probes to a local host through
an interface that has been dropped by the router deamon.
-i iface Specify a network interface to obtain the source IP address for outgoing probe
packets. This is normally only useful on a multi-homed host. The -s
option is also another way to do this. Note that this option does not
provide a way to specify the interface on which the probe packets are
sent.
-m max_ttl Set the maximum ttl used in outgoing probe packets. The default is 30 hops,
which is the same default used for TCP connections.
-p port Set the base UDP port number used in probes. The default is 33434. traceroute
hopes that nothing is listening on UDP ports (base+(nhops- 1)*nqueries)
to (base+(nhops*nqueries)-1)at the destination host, so that an ICMP
PORT_UNREACHABLE message will be returned to terminate the
route tracing. If something is listening on a port in the default range, this
option can be used to select an unused port range.nhops is defined as the
number of hops between the source and the destination.
-q nqueries Set the desired number of probe queries. The default is 3.
-s src_addr Use the following address, which usually is given as an IP address, not a
hostname, as the source address in outgoing probe packets. On multi-
homed hosts, those with more than one IP address, this option can be
used to force the source address to be something other than the IP
address traceroute picks by default. If the IP address is not one of this
machine's interface addresses, an error is returned and nothing is sent.
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 32
When used together with the -i option, the given IP address should be
configured on the specified interface. Otherwise, an error will be
returned.
-t tos Set the tos(type-of-service) in probe packets to the specified value. The default
is zero. The value must be an integer in the range from 0 to
255. Gateways along the path may route the probe packet differently
depending upon the tos value set in the probe packet.
-w waittime Set the time, in seconds, to wait for a response to a probe. The default is five
(5) seconds.
Host The network host.
EXAMPLES
Traceroute computerhope.com - would display results similar to the following:
traceroute to computerhope.com (166.70.10.23), 30 hops max, 40 byte packets 1
198.60.22.1 (198.60.22.1) 2.303 ms 1.424 ms 2.346 ms
2 krunk3.xmission.com (198.60.22.6) 0.742 ms * 1.521 ms
Note: in this example because we are local to the address we are tracerouting the amount of hops
is very minimal. However, when you traceroute computerhope.com you may hop more than we
do. This command is very useful for distinguishing network / router issues. If the domain does not
work or is not available you can traceroute an IP.
NETSTAT
Netstat command netstat displays the contents of various network-related data structures in various
formats, depending on the options you select. The first form of the command displays a list of
active sockets for each protocol. The second form selects one from among various other network
data structures. The third form shows the state of the interfaces. The fourth form displays the
routing table, the fifth form displays the multicast routing table, and the sixth form displays the
state of DHCP on one or all interfaces.
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 33
SYNOPSIS Shows network status.
SYNTAX
netstat [-a] [-n] [-v]
netstat [-g | -m | -p | -s | -f address_family ] [-n] [-P protocol]
netstat [ -i ] [ -I interface ] [ interval ]
netstat -r [-a] [-n] [-v ]
netstat -M [-n] [-s ]
netstat -D [ -I interface ]
-a Show the state of all sockets and all routing table entries; normally, sockets used
by server processes are not shown and only interface, host, network, and
default routes are shown.
-n Show network addresses as numbers. netstat normally displays addresses as
symbols. This option may be used with any of the display formats.
-v Verbose. Show additional information for the sockets and the routing table.
-g Show the multicast group memberships for all interfaces.
-m Show the STREAMS statistics.
-p Show the address resolution (ARP) tables.
-s Show per-protocol statistics. When used with the -M option, show multicast
routing statistics instead.
-i Show the state of the interfaces that are used for TCP/IP traffic.
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 34
-r Show the routing tables.
-M Show the multicast routing tables. When used with the -s option, show multicast
routing statistics instead.
-d Show the state of all interfaces that are under Dynamic Host Configuration
Protocol (DHCP) control.
-D Show the status of DHCP configured interfaces.
-f address_family imit statistics or address control block reports to those of the specified
address_family, which can be one of:
inet For the AF_INET address family
unix For the AF_UNIX address family
-P protocol Limit display of statistics or state of all sockets to those applicable to protocol.
- I interface Show the state of a particular interface. interface can be any valid interface such
as ie0 or
le0.
IFCONFIG
The "ifconfig" command allows the operating system to setup network interfaces and allow the
user to view information about the configured network interfaces.
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 35
SYNTAX
ifconfig [-L] [-m] interface [create] [address_family] [address[/prefixlength] [dest_address]]
[parameters]
ifconfig interface destroy
ifconfig -a [-L] [-d] [-m] [-u] [address_family]
ifconfig -l [-d] [-u] [address_family]
ifconfig [-L] [-d] [-m] [-u] [-C]
Address For the DARPA-Internet family, the address is either a host name present in the
host name data base, or a DARPA Internet address expressed in the
Internet standard ``dot notation''.
It is also possible to use the CIDR notation (also known as the slash notation)
to include the netmask. That is, one can specify an address like
192.168.0.1/16.
addres_family Specify the address family which affects interpretation of the remaining
parameters. Since an interface can receive transmissions in differing
protocols with different naming schemes, specifying the address family
is recommended. The address or protocol families currently supported
are ``inet'', ``inet6'',
dest_address Specify the address of the correspondent on the other end of a point to point
link.
Interface This parameter is a string of the form ``name unit'', for example, ``en0''.
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 36
PING
Sends ICMP ECHO_REQUEST packets to network hosts.
SYNTAX
ping -s [-d] [-l] [-L] [-n] [-r] [-R] [-v] [ -i interface_address ] [-I interval] [-t ttl] host [packetsize]
[count]
-d Set the SO_DEBUG socket option.
-l Loose source route. Use this option in the IP header to send the packet to the
given host and back again. Usually specified with the -R option.
-L Turn off loopback of multicast packets. Normally, if there are members in the
host group on the out- going interface, a copy of the multicast packets
will be delivered to the local machine.
-n Show network addresses as numbers. ping normally displays addresses as host
names.
-r Bypass the normal routing tables and send directly to a host on an attached
network. If the host is not on a directly-attached network, an error is
returned. This option can be used to ping a local host through an
interface that has been dropped by the router daemon.
-R Record route. Sets the IP record route option, which will store the route of the
packet inside the IP header. The contents of the record
ping computerhope.com - Would ping the host computerhope.com to see if it is alive
WHO IS:
WHOIS (pronounced "who is"; not an acronym) is a query/response protocol which is widely used for querying
an official database in order to determine the owner of a domain name, an IP address, or an autonomous system
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 37
number on the Internet. WHOIS lookups were traditionally made using a command line interface, but a number
of simplified web-based tools now exist for looking up domain ownership details from different databases.
WHOIS normally runs on TCP port 43.
The WHOIS system originated as a method that system administrators could use to look up information to contact
other IP address or domain name administrators (almost like a "white pages").
Syntax: whois [ -h HOST ] [ -p PORT ] [ -aCFHlLMmrRSVx ] [ -g SOURCE:FIRST-LAST ] [ -i ATTR ] [ -S
SOURCE ] [ -T TYPE ] object
Example: whois www.google.com
socket
To do network I/O, the first thing a process must do is to call the socket system call, specifying the type of
communication protocol desired
#include
#include
int socket(int family, int type, int protocol);
The family is one of
AF_UNIX -- Unix internal protocols
AF_INET -- Internet protocols
AF_NS -- Xerox NS Protocols
AF_IMPLINK-- IMP link layer
The AF_ prefix stands for "address family." In the first project, we are going to use AF_INET.
The socket type is one of the following:
SOCK_STREAM stream socket
SOCK_DGRAM datagram socket
SOCK_RAW raw socket
SOCK_SEQPACKETsequenced packet socket
SOCK_RDM reliably delivered message socket (not implemented yet)
The protocol argument to the socket system call is typically set to 0 for most user applications. The valid
combinations are shown as follows.
ARP
In computer networking, the Address Resolution Protocol (ARP) is the method for finding a host's link layer
(hardware) address when only its Internet Layer (IP) or some other Network Layer address is known.
ARP has been implemented in many types of networks; it is not an IP-only or Ethernet-only protocol. It can be
used to resolve many different network layer protocol addresses to interface hardware addresses, although, due to
the overwhelming prevalence of IPv4 and Ethernet, ARP is primarily used to translate IP addresses to Ethernet
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 38
MAC addresses.
Arp syntax:
ARP -s inet_addr eth_adr [if_addr]
ARP -d inet_addr [if_addr]
ARP -a [inet_addr] [-N if_addr]
Example: arp -a
Output:
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 39
2 .Implement connection oriented and connection less client for well known
services.
a) Implementation of concurrent connection- oriented echo-services
DESCRIPTION: A sequential server, a concurrent server has to be able to serve more than one
client at a time. For example, a chat server may be serving a specific client for hours--it cannot
wait till it stops serving a client before it serves the next one. This requires a significant change
in our flowchart:
We moved the serve from the daemon process to its own server process. However, because each
child process inherits all open files (and a socket is treated just like a file), the new process inherits
not only the “accepted handle,” i.e., the socket returned by the accept call, but also the top socket,
i.e., the one opened by the top process right at the beginning.
However, the server process does not need this socket and should close it immediately. Similarly,
the daemon process no longer needs the accepted socket, and not only should, but must close it-
-otherwise, it will run out of available file descriptors sooner or later. After the server process is
done serving, it should close the accepted socket. Instead of returning to accept, it now exits.
➢ Under UNIX®, a process does not really exit. Instead, it returns to its parent. Typically, a
parent process waits for its child process, and obtains a return value. However, our daemon
process cannot simply stop and wait. That would defeat the whole purpose of creating additional
processes. But if it never does wait, its children will become zombies--no longer functional but
still roaming around.
➢ For that reason, the daemon process needs to set signal handlers in its initialize daemon phase.
At least a SIGCHLD signal has to be processed, so the daemon can remove the zombie return
values from the system and release the system resources they are taking up.
➢ That is why our flowchart now contains a process signals box, which is not connected to any
other box. By the way, many servers also process SIGHUP, and typically interpret as the signal
from the superuser that they should reread their configuration files. This allows us to change
settings without having to kill and restart these servers. Concurrent Connection-Oriented Servers
• Use TCP for connection-oriented communication. • Call _process () to process one thread to
serve each Client. Example A single-thread, concurrent, connection-oriented server:
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 40
• The thread performs the duties of both the main threadand the service thread.
• It calls select() to identify the ready sockets, and then it serves the clients accordingly.
Example A concurrent, connection-oriented, multiservice serverusing asynchronous I/O:
• The master thread creates one TCP socket to listenrequests for one service, and it uses
asynchronous I/Oto identify the ready sockets.
• When the master thread receives a client’s request, itcreates a slave thread to serve this client.
ALGORITHM:
1. The concurrent client server model is a model which communicates with the client in the
parallel method of communication .For example let us see at the following syntax i.e
…,”listen(sfd,5);”
2. This means that the server is bind to listen for the clients of maximum 5 at a time. In this the
internal process is done as below.
3. Not like in the normal or iterative client server model the server in the concurrent client server
model communicates with all the 5 clients at the same time using the ability of “fork()
4. That is the fork() is a command that develops duplicate process or a parent and child process.
5. Like wise the server is like a parent process which creates a child process separately for all the
incoming clients .So that the communication process is completed as in normal or iterative
client server process.
6. This is the main functionality of concurrent client and server model
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 42
(a) concurrent server connectionoriented
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
main(int argc, char *argv[])
{
int sockfd,new_sockfd,rval,pid;
char buff1[20],buff2[20];
struct sockaddr_in server, client;
int len;
sockfd=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(sockfd==-1)
{
perror("\n SOCK_ERR\n");
exit(1);
}
server.sin_family=AF_INET;
server.sin_addr.s_addr=inet_addr("192.168.122.1");
server.sin_port=htons(3339);
rval=bind(sockfd,(struct sockaddr*)&server,sizeof(server));
if(rval!=-1)
{
listen(sockfd,5);
while(1)
{
new_sockfd=accept(sockfd,(struct sockaddr*)&client,&len);
if(new_sockfd!=-1)
{
pid=fork();
if(pid==0)
{
printf("\n child process executing \n");
printf("\n child process is is %d", getpid());
len=sizeof(server);
rval=recv(new_sockfd, buff1,sizeof(buff1),0);
if(rval==-1)
{
perror("\n RECV_ERR\n");
exit(1);
}
else
{
printf("\n received message is %s\n", buff1);
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 43
}
rval=send(new_sockfd,buff1,sizeof(buff1),0);
if(rval!=-1)
{
printf("\n message sent successfully \n");
}
else
{
perror("\nSEND_ERR\n");
exit(1);
}
}
else
{
printf("\n parent process\n");
printf("parent process id is %d \n", getppid());
exit(1);
}
}
else
{
perror("\n ACCEPT_ERR\n");
exit(1);
}
}
}
else
{
perror("\nBIND_ERR\n");
close(sockfd);
}
}
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 44
Concurrent client connection oreniented
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include<netinet/in.h>
#include <arpa/inet.h>
main(int argc, char *argv[])
{
int sockfd, rval;
char buff1[20],buff2[20];
struct sockaddr_in server, client;
int len;
sockfd=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(sockfd==-1)
{
perror("\n SOCK_ERR\n");
exit(1);
}
server.sin_family=AF_INET;
server.sin_addr.s_addr=inet_addr("192.168.122.1");
server.sin_port=htons(3339);
rval=connect(sockfd,(struct sockaddr *)&server, sizeof(server));
if(rval!=-1)
{
printf("\n enter a message \n");
scanf("%s", buff1);
rval=send(sockfd,buff1,sizeof(buff1),0);
if(rval==-1)
{
perror("\n SEND_ERR\n");
exit(1);
}
rval=recv(sockfd,buff2,sizeof(buff2),0);
if(rval!=-1)
{
printf("\n Received message is %s \n", buff2);
}
else
{
perror("\nRECV_ERR\n");
exit(1);
}
}
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 45
else
{
printf("\n CONNECT_ERR\n");
exit(1);
}
}
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 46
b) Implementation of concurrent connection- less echo-services
Description:
Concurrent Connectionless: It is rarely used server design, where server create a new process to attend
each request from the client, this concurrently provides the efficiency in the system but the time to
create new process must be considerably less than the time required to compute the request.
Generally, in this concurrent connectionless server design cost put for process creation become higher
than the efficiency achieved with the concurrency. So, it is uncommonly used.
ALOGRITHM:
1. The concurrent client server model is a model which communicates with the client in the parallel
method of communication .
2. Not like in the normal or iterative client server model the server in the concurrent client server
model communicates with all the clients at the same time using the ability of “fork()”.
3. That is the fork() is a command that develops duplicate process or a parent and child process.
4. Like wise the server is like a parent process which creates a child process separately for all the
incoming clients .So that the communication process is completed as in normal or iterative client
server process.
5. This is the main functionality of concurrent client and server model.
Flowchart
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 47
concurrent connection less server
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
main(int argc, char *argv[])
{
int sockfd,rval,pid;
char buff1[20],buff2[20];
struct sockaddr_in server, client;
int len;
sockfd=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
if(sockfd==-1)
{
}
server.sin_family=AF_INET;
server.sin_addr.s_addr=inet_addr("192.168.122.1");
server.sin_port=htons(3221);
rval=bind(sockfd,(struct sockaddr*)&server,sizeof(server));
if(rval!=-1)
{
pid=fork();
if(pid==0)
{
printf("\n Childprocess Executing \n");
printf("\n child process ID Is:%d\n", getpid());
len=sizeof(client);
rval=recvfrom(sockfd, buff1,sizeof(buff1),0,(struct sockaddr*)&client,&len);
if(rval==-1)
{
perror("\n RECV_ERR\n");
exit(1);
}
else
{printf("\n Received Message Is:%s\n",buff1);
}
rval=sendto(sockfd,buff1,sizeof(buff1),0,(struct sockaddr*)&client,sizeof(client
));
if(rval!=-1)
{
printf("\n Message sent successfully \n");
}
else
{
perror("\n SEND_ERR\n");
exit(1);
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 48
}
}
else
printf("\n parent process\n");
printf("parent process ID is %d\n", getppid());
}
else
{
perror("\n BIND_ERR\n");
exit(1);
}
}
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 49
concurrent connection less client
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include<netinet/in.h>
#include <arpa/inet.h>
main(int argc, char *argv[])
{
int sockfd, rval;
char buff1[20],buff2[20];
struct sockaddr_in server, client;
int len;
sockfd=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
if(sockfd==-1)
{
perror("\n SOCK_ERR\n");
exit(1);
}
server.sin_family=AF_INET;
server.sin_addr.s_addr=inet_addr("192.168.122.1");
server.sin_port=htons(3221);
printf("\n enter a message \n");
scanf("%s", buff1);
rval=sendto(sockfd, buff1, sizeof(buff1),0,(struct sockaddr*)&server,sizeof(serv er));
if(rval!=-1)
{
printf("\nmessage sent successfully\n");
}
else
{
perror("\n SEND_ERR\n");
exit(1);
}
len=sizeof(server);
rval=recvfrom(sockfd,buff1,sizeof(buff1),0,(struct sockaddr*)&server,&len);
if(rval==-1)
{
perror("\nRECV_ERR\n");
exit(1);
}
else
{
printf("\n Received Message is %s\n", buff1);
}
}
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 50
3. Implementation of Concurrent Server using connection oriented sockets
systems calls Daytime service.
DESCRIPTION
TCP Based Daytime Service
One daytime service is defined as a connection based application on TCP. A server listens for TCP
connections on TCP port 13. Once a connection is established the current date and time is sent out
the connection as a ascii character string (and any data received is thrown away). The service
closes the connection after sending the quote.
UDP Based Daytime Service
Another daytime service service is defined as a datagram based application on UDP. A server
listens for UDP datagrams on UDP port13. When a datagram is received, an answering datagram
is sent containing the current date and time as a ASCII character string (the data in the received
datagram is ignored).
Daytime Syntax
There is no specific syntax for the daytime. It is recommended that it be limited to the ASCII
printing characters, space, carriage return, and line feed. The daytime should be just one line. One
popular syntax is: Weekday, Month Day, Year Time-Zone
Example:
Tuesday, February 22, 1982 17:37:43-PST
Daytime Protocol
Another popular syntax is that used in SMTP:
dd mmm yy hh:mm:ss zzz
Example: 02 FEB 82 07:59:01 PS
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 51
ALGORITHM:
1. This is the implementation of the daytime using TCP method. In this program the time is
denoted in some formatted type as below
DAY TIME IS --- >15 FEB 2010 16:23:24 IST
2. In this program the standard port number used is “13”
3. The type of the family used is AF_INET and the port no used is”13”and internet address
used is “192.168.122.1” .
4. The socket is created in the program uses the SOCK_STREAM method which corresponds
to the TCP protocol .
5. The headers implemented are “stdio.h” ,”sys/socket.h”,netinet/in.h”.
6. The first one is the standard input output file,the second is the type of the connection that
is implementation in the program ,the third is the socket creation file, the last one is the
internetprotocol.
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 52
Day Time Service
//server
#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<time.h>
#include<string.h>
#include<stdlib.h>
#define max 30
#define PORT 2100
int main()
{
int sersoc,clisoc,conn,len,wri;
char str[max];
pid_t pid;
time_t ticks;
socklen_t clilen;
struct sockaddr_in servaddr,cliaddr;
servaddr.sin_family=AF_INET;
servaddr.sin_port=htons(PORT);
servaddr.sin_addr.s_addr=inet_addr("192.168.122.1");
if((sersoc=socket(AF_INET,SOCK_STREAM,0))<0)
{
perror("Socket Error");
exit(0);
}
if(bind(sersoc,(struct sockaddr *)&servaddr,sizeof(servaddr))<0)
{
perror("Bind Error");
exit(0);
}
listen(sersoc,10);
for(;;)
{
len=sizeof(cliaddr);
conn=(accept(sersoc,(struct sockaddr *)&clisoc,&len));
if((pid=fork())==0)
{
close(sersoc);
ticks=time(NULL);
strcpy(str,ctime(&ticks));
if(wri==(write(conn,str,sizeof(str),0))<0)
{
printf("Write current date and time");
exit(0);
}
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 53
close(conn);
exit(0);
}
close(conn);
}
close(sersoc);
return 0;
}
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 54
//Client
#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<time.h>
#include<string.h>
#include<arpa/inet.h>
#include<stdlib.h>
#define CLI_PORT 2100
#define BUFF_SIZE 30
int main(int argc,char **argv)
{
int clisoc,re;
char recbuff[BUFF_SIZE];
struct sockaddr_in cliaddr;
bzero(&cliaddr,sizeof(cliaddr));
cliaddr.sin_family=AF_INET;
cliaddr.sin_port=htons(CLI_PORT);
cliaddr.sin_addr.s_addr=inet_addr("192.168.122.1");
if((clisoc=socket(AF_INET,SOCK_STREAM,0))<0)
{
perror("Socket Errror");
exit(0);
}
if((connect(clisoc,(struct sockaddr *)&cliaddr,sizeof(cliaddr)))<0)
{
perror("Connect Error");
exit(0);
}
if((re=(read(clisoc,recbuff,sizeof(recbuff),0)))<0)
{
printf("Read Error");
exit(0);
}
printf("The Current Date and Time : %s\n",recbuff);
close(clisoc);
return 0;
}
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 55
b) Implementation of time services using connection oriented sockets systems
calls.
DESCRIPTION
The TIME service is an Internet protocol. Its purpose is to provide a site-independent, machine
readable date and time. Time can operate over either TCP or UDP. When operating over TCP, a
host connects to a server that supports the TIME protocol on TCP port 37. The server then sends
the time as a 32-bit unsigned binary number in network byte order representing a number of
seconds since 00:00 (midnight) 1 January, 1900 GMT and closes the connection. The host receives
the time and closes the connection.
When operating over UDP, the client sends a (typically empty) datagram to UDP port 37. The
server responds with a single datagram of length 4 containing the time. There is no connection
setup or teardown. The TIME protocol is used by the Linux rdate command. The TIME protocol
has been superseded by the Network Time Protocol (NTP).
Time Protocol
This RFC specifies a standard for the ARPA Internet community. Hosts on the ARPA Internet that
choose to implement a Time Protocol are expected to adopt and implement this standard.
This protocol provides a site-independent, machine readable date and time. The Time service sends
back to the originating source the time in seconds since midnight on January first 1900.
One motivation arises from the fact that not all systems have a date/time clock, and all are subject
to occasional human or machine error. The use of time-servers makes it possible to quickly confirm
or correct a system's idea of the time, by making a brief poll of several
independent sites on the network.
This protocol may be used either above the Transmission Control Protocol (TCP) or above the
User Datagram Protocol (UDP). When used via TCP the time service works as follows:
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 56
S: Listen on port 37 (45 octal).
U: Connect to port 37.
S: Send the time as a 32 bit binary number.
U: Receive the time.
U: Close the connection.
S: Close the connection.
The server listens for a connection on port 37. When the connection is established, the server
returns a 32-bit time value and closes the connection. If the server is unable to determine the time
at its site, it should either refuse the connection or close it without sending anything. When used
via UDP the time service works as follows:
S: Listen on port 37 (45 octal).
U: Send an empty datagram to port 37.
S: Receive the empty datagram.
S: Send a datagram containing the time as a 32 bit binary number.
U: Receive the time datagram.
The server listens for a datagram on port 37. When a datagram arrives, the server returns a
datagram containing the 32-bit time value. If the server is unable to determine the time at its site,
it should discard the arriving datagram and make no reply.
The time is the number of seconds since 00:00 (midnight) 1 January 1900
GMT, such that the time 1 is 12:00:01 am on 1 January 1900 GMT; this base will serve until the year
2036.
For example: the time 2,208,988,800 corresponds to 00:00 1 Jan 1970 GMT,
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 57
2,398,291,200 corresponds to 00:00 1 Jan 1976 GMT,
2,524,521,600 corresponds to 00:00 1 Jan 1980 GMT,
2,629,584,000 corresponds to 00:00 1 May 1983 GMT,
and -1,297,728,000 corresponds to 00:00 17 Nov 1858 GMT.
ALGORITHM
1. This program implements the time using TCP protocol in the integer formatted way such
that it gives the total time in seconds from some reference point.
2. It is shown in the example below:
Tme is -> 3475219317
3. In this program the standard port number used is “37”.
4. The type of the family used is AF_INET and the port no used is”13”and Internet address
used is “192.168.0.5” .
5. The socket is created in the program uses the SOCK_STREAM method which
corresponds to the TCP protocol
6. The headers implemented are “stdio.h” ,”sys/socket.h”,netinet/in.h”.
7. The first one is the standard input output file,the second is the type of the connection
that is implementation in the program ,the third is the socket creation file, the last one is
the internet protocol
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 58
Time Service
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#define ERROR -1
main()
{
unsigned long timeval, tempval;
int sfd;
struct sockaddr_in serv_addr;
sfd=socket(AF_INET,SOCK_STREAM,0);
if(sfd==ERROR)
{
perror("socket failed");
exit(1);
}
serv_addr.sin_family=AF_INET;
serv_addr.sin_addr.s_addr=inet_addr("192.168.0.5");
serv_addr.sin_port=htons(37);
if(connect(sfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr))==ERROR)
{
perror("connection failed");
exit(1);
}
read(sfd,&tempval,80);
timeval=htonl(tempval);
printf("\n TIME BY USING TCP \n");
printf("\n \t TIME is ---> %u\n \n", timeval);
close(sfd);
}
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 59
4. Implementation of concurrent server using connection less client using socket
system calls, Echo Service.
Implementation of concurrent connection- less echo-services
ALOGRITHM:
1. The concurrent client server model is a model which communicates with the client
in the parallel method of communication .
2. Not like in the normal or iterative client server model the server in the concurrent
client server model communicates with all the clients at the same time using the
ability of “fork()”.
3. That is the fork() is a command that develops duplicate process or a parent and
child process.
4. Like wise the server is like a parent process which creates a child process
separately for all the incoming clients .So that the communication process is
completed as in normal or iterative client server process.
5. This is the main functionality of concurrent client and server model.
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 60
(a) concurrent connection less server
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
main(int argc, char *argv[])
{
int sockfd,rval,pid;
char buff1[20],buff2[20];
struct sockaddr_in server, client;
int len;
sockfd=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
if(sockfd==-1)
{
}
server.sin_family=AF_INET;
server.sin_addr.s_addr=inet_addr("192.168.122.1");
server.sin_port=htons(3221);
rval=bind(sockfd,(struct sockaddr*)&server,sizeof(server));
if(rval!=-1)
{
pid=fork();
if(pid==0)
{
printf("\n Childprocess Executing \n");
printf("\n child process ID Is:%d\n", getpid());
len=sizeof(client);
rval=recvfrom(sockfd, buff1,sizeof(buff1),0,(struct sockaddr*)&client,&len);
if(rval==-1)
{
perror("\n RECV_ERR\n");
exit(1);
}
else
{
printf("\n Received Message Is:%s\n",buff1);
}
rval=sendto(sockfd,buff1,sizeof(buff1),0,(struct sockaddr*)&client,sizeof(client
));
if(rval!=-1)
{
printf("\n Message sent successfully \n");
}
else
{
perror("\n SEND_ERR\n");
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 61
exit(1);
}
}
else
printf("\n parent process\n");
printf("parent process ID is %d\n", getppid());
}
else
{
perror("\n BIND_ERR\n");
exit(1);
}
}
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 62
(b) concurrent connection less client
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include<netinet/in.h>
#include <arpa/inet.h>
main(int argc, char *argv[])
{
int sockfd, rval;
char buff1[20],buff2[20];
struct sockaddr_in server, client;
int len;
sockfd=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
if(sockfd==-1)
{
perror("\n SOCK_ERR\n");
exit(1);
}
server.sin_family=AF_INET;
server.sin_addr.s_addr=inet_addr("192.168.122.1");
server.sin_port=htons(3221);
printf("\n enter a message \n");
scanf("%s", buff1);
rval=sendto(sockfd, buff1, sizeof(buff1),0,(struct sockaddr*)&server,sizeof(serv
er));
if(rval!=-1)
{
printf("\nmessage sent successfully\n");
}
else
{
perror("\n SEND_ERR\n");
exit(1);
}
len=sizeof(server);
rval=recvfrom(sockfd,buff1,sizeof(buff1),0,(struct sockaddr*)&server,&len);
if(rval==-1)
{
perror("\nRECV_ERR\n");
exit(1);
}
else
{
printf("\n Received Message is %s\n", buff1);
}
}
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 63
4. Program to demonstrate iterative server using connection-oriented socket sys call (Emp
sal)
Description: The problem can be implemented using sockets. General implementation steps are as
follows: Steps involved in writing the Server Process:
1. Create a socket using socket( ) system call..
2. Bind server’s address and port using bind( ) system call.
3. Convert the socket into a listening socket using listen( ) sytem call.
4. Wait for client connection to complete using accept( ) system call.
5. Receive the Client request using recv() system call which consist of the name of
the command that is to be executed along with data parameters(if any)
6. The command is interpreted and executed.
7. On successful execution the result is passed back to the client by the server
Steps involved in writing the Client Process:
1. Create a socket.
2. Fill in the internet socket address structure (with server information).
3. Connect to server using connect system call.
4. The client passes the command and data parameters (if any) to the server.
5. Read the result sent by the server, write it to standard output.
6. Close the socket connection.
Flowchart
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 64
Employee server:
#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<stdlib.h>
struct emp
{
float basic;
float da;
float hra;
};
int main(int argc,char *argv[])
{
int sockfd,rval,nsfd;
struct emp e;
float net_sal,epf=2000,pt=200;
struct sockaddr_in s,c;
socklen_t clen;
s.sin_family=AF_INET;
s.sin_port=htons(atoi(argv[2]));
s.sin_addr.s_addr=inet_addr(argv[1]);
sockfd=socket(AF_INET,SOCK_STREAM,0);
if(sockfd<0)
{
perror("SER:unable to create the socket...");
exit(1);
}
printf("\nSER:the socket has been created...%d",sockfd);
rval=bind(sockfd,(struct sockaddr*)&s,sizeof(s));
if(rval<0)
{
perror("SER:unable to bind..");
exit(1);
}
printf("\nSER:socket binded successfully");
listen(sockfd,5);
while(1)
{
clen=sizeof(c);
nsfd=accept(sockfd,(struct sockaddr*)&c,&clen);
if(nsfd<0)
{
perror("\n SER:unable to accept incoming request..");
exit(1);
}
rval=recv(nsfd,(struct emp*)&e,sizeof(e),0);
if(rval<0)
{
perror("\n SER:unable to recieve..");
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 65
exit(1);
}
printf("\nSER:basic,da,hra are %f,%f,%f",e.basic,e.da,e.hra);
net_sal=e.basic+(e.da*e.basic)+(e.hra*e.basic)-pt-epf;
printf("\nSER:the net salary at server is ...%f",net_sal);
rval=send(nsfd,(float *)&net_sal,sizeof(net_sal),0);
if(rval<0)
{
perror("\n SER:unable to send..");
exit(1);
}
printf("\n SER:message echoed from client is..");
close(nsfd);
exit(1);
}
}
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 66
Employee client:
#include<stdlib.h>
#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
struct emp
{
float basic;
float da;
float hra;
};
int main(int agrc,char *argv[])
{
int sfd,rval;
struct emp e;
float net_sal;
struct sockaddr_in s;
s.sin_family=AF_INET;
s.sin_port =htons(atoi(argv[2]));
s.sin_addr.s_addr=inet_addr(argv[1]);
sfd=socket(AF_INET,SOCK_STREAM,0);
if(sfd<0)
{
perror("unable to create a socket");
exit(1);
}
rval=connect(sfd,(struct sockaddr*)&s,sizeof(s));
if(rval<0)
{
perror("unable to connect to the server for echo\n");
exit(1);
}
printf("\n connection establish successfully\n");
printf("\nCLI:enter the basic salary\n");
scanf("\n%f",&e.basic);
printf("\n CLI enter the DA");
scanf("\n%f",&e.da);
printf("\nCLI :enter the HRA\n");
scanf("\n%f",&e.hra);
printf("\nCLI basic,da and hra are %f,%f,%f",e.basic,e.da,e.hra);
rval=send(sfd,(struct emp*)&e,sizeof(e),0);
rval=recv(sfd,(float *)&net_sal,sizeof(net_sal),0);
if(rval<0)
{
perror("unable to recieve");
exit(1);
}
printf("\nCLI:the net salary of employee is %f",net_sal);
}
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 67
6. Implementation of iterative server using connection-less socket system call (Student grade)
DESCRIPTION
Iterative Connectionless Server
• Some iterative servers use UDP because
(1) iterative design is suitable for services with a small service time, (2) UDP has a lower overhead
than TCP.
• The server uses an unconnected socket to receive datagrams from arbitrary clients.
• The server calls recvfrom() to receive a client’s requestand extracts the client’s endpoint address.
• The server calls sendto() to send a reply message to theclient’s endpoint address.
An iterative, connectionless, multiservice server using asynchronous I/O:
• It uses one UDP socket for each service.
• It uses asynchronous I/O to identify the ready sockets.
• It uses a single thread to provide all the services.
ALGORITHM:
1. The program is used for the communication of client with the server. In this program the
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 68
server listens to the no of clients .
2. The client program connects with the server through the”connect”system call and the
server binds with the client with”bind”system call.this implements the socket method.
3. This also consists of the AF_INET family and SOCK_DGRAM implementation with
protocol suit determined by the operating system.
4. The server and client communications in the string data exchanging manner.In this the
server takes the requests and gives services to the clients.
5. That is which client communications first the server will reply. This all are queued in a
stack.
Flowchart
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 69
//Server
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
int main()
{
int sockfd,marks1,marks2,marks3,percentage;
char grade[10];
socklen_t clilen;
struct sockaddr_in sa;
struct sockaddr_in ca;
sockfd=socket(AF_INET,SOCK_DGRAM,0);
sa.sin_family = AF_INET;
sa.sin_port = htons(6500);
sa.sin_addr.s_addr=inet_addr("192.168.122.1");
bind(sockfd,(struct sockaddr*)&sa,sizeof(sa));
listen(sockfd,5);
for(;;)
{
clilen=sizeof(ca);
read(sockfd,&marks1,sizeof(marks1));
read(sockfd,&marks2,sizeof(marks2));
read(sockfd,&marks3,sizeof(marks3));
printf("SER: marks1,marks2,marks3 are %d,%d,%d",marks1,marks2,marks3);
percentage=(marks1+marks2+marks3)/3;
if(percentage>=80)
{
strcpy(grade,"Grade: A");
}
else if (percentage>=70 && percentage<80)
{
strcpy(grade,"Grade:B");
}
else if (percentage>=60 && percentage<70)
{
strcpy(grade," Grade : C");
}
else if (percentage>=40 && percentage<60)
{
strcpy(grade," Grade : D");
}
else
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 70
{
strcpy(grade,"fail");
}
printf("\n SER: grade at server is ---%s",grade);
write(sockfd,&grade,sizeof(grade));
exit(1);
}
}
//client
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
int main() {
int sockfd;
struct sockaddr_in sa;
socklen_t servlen;
int marks1,marks2,marks3,percentage;
char grade[10];
sockfd=socket(AF_INET,SOCK_DGRAM,0);
sa.sin_family=AF_INET;
sa.sin_port = htons(6500);
sa.sin_addr.s_addr = inet_addr("192.168.122.1");
servlen = sizeof(sa);
printf("enter the marks of all subjects\n");
printf("enter first subject marks \n");
scanf("%d",&marks1);
printf("enter second subject marks \n");
scanf("%d",&marks2);
printf("enter third subject marks \n");
scanf("%d",&marks3);
write(sockfd,&marks1,sizeof(marks1));
write(sockfd,&marks2,sizeof(marks2));
write(sockfd,&marks3,sizeof(marks3));
read(sockfd,&grade,sizeof(grade));
printf ("result is %s\n", grade);
close(sockfd); }
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 71
7. Demonstrate the use of Advanced socket system call (readv,writev)
READV, WRITEV: read or write a vector
#include <sys/uio.h>
int readv(int fd, const struct iovec * vector, int count);
int writev(int fd, const struct iovec * vector, int count);
struct iovec {
ptr_t iov_base; /* Starting address. */
size_t iov_len; /* Length in bytes. */
};
DESCRIPTION
readv reads data from file descriptor fd, and puts the result in the buffers described by vector. The
number of buffers is specified by count. The buffers are filled in the order specified. Operates just
like read except that data is put in vector instead of a contiguous buffer.
writev writes data to file descriptor fd, and from the buffers described by vector. The number of
buffers is specified by count. The buffers are used in the order specified. Operates just like
write except that data is taken from vector instead of a contiguous buffer.
RETURN VALUE
On success readv returns the number of bytes read. On success writev returns the number of bytes
written. On error, -1 is returned, and errno is set appropriately.
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 72
ERRORS
EINVAL An invalid argument was given. For instance count might be greater than MAX_IOVEC,
or zero. fd could also be attached to an object which is unsuit able for
reading (for readv) or writing (for writev).
EFAULT "Segmentation fault." Most likely vector or some of the iov_base pointers points to
memory that is not properly allocated.
ALGORITHM:
1. Set-up the base-address using the iovector() function.
2. Creating a connection-Oriented server socket
3. Binding the structure to the server socket.
4. Listen to indicate that it is ready to receive connections
5. Accept takes the first connection request.
6. At the client’s side , connect system call to establish a connection with a server.
7. For multiple reads and multiple writes , multiple buffers are used.
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 73
Implemention of writev
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/uio.h>
#include <fcntl.h>
main()
{
char s1[20],s2[20],s3[20],s4[20];
struct iovec iov[4];
int fd;
fd=open("file.txt",O_WRONLY);
printf("enter 1st string\n");
scanf("%s",&s1);
printf("enter 2nd string\n");
scanf("%s",&s2);
printf("enter 3rd string\n");
scanf("%s",&s3);
printf("enter 4th string\n");
scanf("%s",&s4);
iov[0].iov_base=s1;
iov[0].iov_len=sizeof(s1);
iov[1].iov_base=s2;
iov[1].iov_len=sizeof(s2);
iov[2].iov_base=s3;
iov[2].iov_len=sizeof(s3);
iov[3].iov_base=s4;
iov[3].iov_len=sizeof(s4);
writev(fd, (struct iovec*) &iov, 4);
}
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 74
implementation of readv
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/uio.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <fcntl.h>
main()
{
char s1[20],s2[20],s3[20],s4[20];
struct iovec iov[4];
int fd;
iov[0].iov_base=s1;
iov[0].iov_len=sizeof(s1);
iov[1].iov_base=s2;
iov[1].iov_len=sizeof(s2);
iov[2].iov_base=s3;
iov[2].iov_len=sizeof(s3);
iov[3].iov_base=s4;
iov[3].iov_len=sizeof(s4);
fd=open("file.txt",O_RDONLY);
readv(fd, (struct iovec*) &iov,4);
printf("first string is %s\n",s1);
printf("second string is %s\n",s2);
printf("third string is %s \n",s3);
printf("fourth string is %s \n",s4);
}
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 75
setsock(),getsock()
SETSOCKOPT,GETSOCKOPT:get and set options on sockets
#include <sys/types.h>
#include <sys/socket.h>
int getsockopt(int s, int level, int optname, void *optval, socklen_t *optlen);
int setsockopt(int s, int level, int optname, const void *optval, socklen_t optlen);
DESCRIPTION
Getsockopt and setsockopt manipulate the options associated with a socket. Options may exist at
multiple protocol levels; they are always present at the uppermost socket level. When manipulating
socket options the level at which the option resides and the name of the option must be specified.
To manipulate options at the socket level, level is specified as SOL_SOCKET. To manipulate
options at any other level the protocol number of the appropriate protocol controlling the option is
supplied. For example, toindicate that an option is to be interpreted by the TCP protocol, level
should be set to the protocol number of TCP. The parameters optval and optlen are used to access
option values for setsockopt. For getsockopt they identify a buffer in which the value for the
requested option(s) are to be returned. For getsockopt, optlen is a value-result parameter, initially
containing the size of the buffer pointed to by optval, and modified on return to indicate the
actual size of the value returned. If no option value is to be supplied or returned, optval may be
NULL. Optname and any specified options are passed uninterpreted to the appropriate protocol
module for interpretation. The include file <sys/socket.h> contains definitions for socket level
options, described below. Options at other protocol levels vary in format and name; consult the
appropriate entries in section 4 of the manual. Most socket-level options utilize an int parameter
for optval. For setsockopt, the parameter should be non-zero to enable a boolean option, or zero if
the option is to be disabled.
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 76
RETURN VALUE On success, zero is returned. On error, -1 is returned, and errno is set
appropriately.
GETSOCKNAME: - get socket name
#include <sys/socket.h>
int getsockname(int s , struct sockaddr * name , socklen_t * namelen )
DESCRIPTION
Getsockname returns the current name for the specified socket. The namelen parameter should
be initialized to indicate the amount of space pointed to by name. On return it contains the
actual size of the name returned(in bytes).
RETURN VALUE On success, zero is returned. On error, -1 is returned, and errno is set
appropriately.
ERRORS EBADF The argument s is not a valid descriptor.
ALGORITHM:
1. int getsockopt(int s, int level, int optname, void *optval, socklen_t *optlen);
2. int setsockopt(int s, int level, int optname, const void *optval, socklen_t
optlen);
3. When manipulating socket options the level at which the option resides and the name of
the option must be specified. To manipulate options at the socket level, level is specified
as SOL_SOCKET. To manipulate options at any other level the protocol number of the
appropriate protocol controlling the option is supplied. For example, to indicate that an
option is to be interpreted by the TCP protocol, level should be set to the protocol number
of TCP; see getprotoent(3).
4. For getsockopt, optlen is a value-result parameter, initially containing the size of the buffer
pointed to by optval, and modified on return to indicate the actual size of the
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 77
value returned. If no option value is to be supplied or returned, optval may be NULL.
Optname and any specified options are passed uninterpreted to the appropriate protocol
module for interpretation.
#include<stdio.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <fcntl.h>
#include <netinet/tcp.h>
#include <sys/types.h>
main(int argc,char *argv[])
{
int sockfd,a,b,c;
sockfd=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
int len=sizeof(a);
char s[20];
getsockopt(sockfd,IPPROTO_TCP,TCP_MAXSEG,&a,&len);
{
printf("PROTOCOL LEVEL>Da Max Segment Size is :%d\n", a);
}
getsockopt(sockfd,IPPROTO_TCP,TCP_NODELAY,s,len);
getsockopt(sockfd,IPPROTO_TCP,TCP_NODELAY,&b,&len);
{
printf("PROTOCOL LEVEL>Da option value is:%d\n", b);
}
setsockopt(sockfd,SOL_SOCKET,SO_KEEPALIVE,s,len);
getsockopt(sockfd,SOL_SOCKET,SO_KEEPALIVE,&c,&len);
{
printf("SOCKET LEVEL>Da option value is %d\n",c);
}
}
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 78
getpeername()
GETPEERNAME : get name of connected peer
#include <sys/socket.h>
int getpeername(int s, struct sockaddr *name, socklen_t *namelen);
DESCRIPTION
Getpeername returns the name of the peer connected to socket s. The namelen parameter should
be initialized to indicate the amount of space pointed to by name. On return it contains the actual
size of the name returned(in bytes). The name is truncated if the buffer provided is too small.
RETURN VALUE
On success, zero is returned. On error, -1 is returned, and errno is set appropriately.
ALGORITHM:
1. Create a TCP socket and fill the internet socket address structure with server IP
addresses and port number
2. Bind the server with known part to the socket created by calling ‘bind’ command.
3. Convert the socket created to listening socket or by calling ‘listen’ command.
4. Then by calling ‘getsockname’ function the local address details of socket are obtained.
5. Then by using the displaying function the details of IP
6. Address , port number are displayed at the standard output.
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 79
Getpeername
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/types.h>
#define ERROR -1
main()
{
int s,k;
struct sockaddr_in server, addr;
socklen_t len;
s=socket(AF_INET,SOCK_STREAM,0);
server.sin_family=AF_INET;
inet_aton("192.168.122.1", &server.sin_addr);
server.sin_port=htons(80);
k=connect(s,(struct sockaddr *)&server, sizeof(server));
if(k<0)
{
perror("connect");
exit(0);
}
len = sizeof(addr);
getpeername(s, (struct sockaddr*)&addr, &len);
printf("Peer IP address: %s\n", inet_ntoa(addr.sin_addr));
printf("Peer port : %d\n", ntohs(addr.sin_port));
}
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 80
8. Implementation of Remote command execution using shell command
Algorithm:
1. The program is used for the communication of client with the server. In this program
the server listens to the client defined in the program as”listen(sfd,5);”.
2. The example illustrates as the server listens to the maximum of 5 clients at a time.
3. The client program connects with the server through the”connect”system call and the
server binds with the client with”bind”system call. this implements the socket method.
4. This also consists of the AF_INET family and SOCK_STREAM implementation with
protocol suit determined by the operating system.
5. The server and client communications in the string data exchanging manner. In this the
server listens to the clients and display the shell commands.
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 81
(a) Remote command execution server using any shell commands
#include <stdio.h>
#include<fcntl.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
main(int argc,char *argv[])
{
int sockfd, new_sockfd, rval, fd;
char buff1[400],buff2[400];
struct sockaddr_in server, client;
int len;
sockfd=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(sockfd==-1)
{
perror("\nsock_error\n");
exit(1);
}
server.sin_family=AF_INET;
server.sin_addr.s_addr=inet_addr(argv[1]);
server.sin_port=htons(atoi(argv[2]));
rval=bind(sockfd,(struct sockaddr*)&server,sizeof(server));
if(rval!=-1)
{
listen(sockfd,5);
while(1)
{
len=sizeof(client);
new_sockfd=accept(sockfd,(struct sockaddr*)&client,&len);
if(new_sockfd!=-1)
{
rval=recv(new_sockfd,buff1,sizeof(buff1),0);
if(rval==-1)
{
perror("\n recev_error\n");
exit(1);
}
else
{
strcat(buff1,">file.txt"); system(buff1);
fd=open("file.txt",O_RDONLY,0666);
if(fd==-1)
{
printf("\n file_error\n");
exit(1);
}
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 82
read(fd,buff2,sizeof(buff2));
}
rval=send(new_sockfd,buff2,sizeof(buff2),0);
if(rval!=-1)
{
printf("\n message sent successfully!\n");
}
else
{
perror("\n send_error\n");
exit(1);
}
}
else
{
perror("\n accept_error");
exit(1);
}
}
}
else
{
perror("\n bind_error\n");
close(sockfd);
}
}
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 83
(b) Remote command execution client using any shell commands
#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include<netinet/in.h>
main(int argc, char *argv[])
{
int sockfd,rval;
char buff1[400],buff2[400];
struct sockaddr_in server;
sockfd=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(sockfd==-1)
{
perror("\nSOCK_ERR\n");
exit(1);
}
server.sin_family=AF_INET;
server.sin_addr.s_addr=inet_addr(argv[1]);
server.sin_port=htons(atoi(argv[2]));
rval=connect(sockfd,(struct sockaddr*)&server,sizeof(server));
if(rval!=-1)
{
printf("\n Enter any shell command: \n");
scanf("%s",buff1);
rval=send(sockfd,buff1,sizeof(buff1),0);
if(rval==-1)
{
perror("\nSEND_ERR\n");
exit(1);
}
rval=recv(sockfd,buff2,sizeof(buff2),0);
if(rval!=-1)
{
printf("\n received data is:%s\n", buff2);
}
else
{
printf("\n RECV_ERR\n");
}
}
else
{
perror("\nCONNECT_ERR\n");
}
}
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 84
9. Implementation of Remote Procedure call using Socket system calls.
DESCRIPTION : RPC is a network programming model for point-to-point communication within
or between software applications.
In RPC, the sender makes a request in the form of a procedure, function, or method call. RPC translates
these calls into requests sent over the network to the intended destination. The RPC recipient then processes
the request based on the procedure name and argument list, sending a response to the sender when complete.
RPC applications generally implement software modules called "proxies" and "stubs" that broker the remote
calls and make them appear to the programmer the same as local procedure calls (LPC). RPC calling
applications usually operate synchronously, waiting for the remote procedure to return a result. RPC
incorporates timeout logic to handle network failures or other situations where RPCs do not return. RPC
has been a common programming technique in the Unix world since the 1990s. The Open Systems
Foundation (OSF) Distributed Computing Environment (DCE) and Sun Microsystems Open Network
Computing (ONC) libraries both were widely deployed. More recent examples of RPC technologies include
Microsoft DCOM, Java RMI, and XML-RPC and SOAP.Remote procedure call (RPC) is an Inter-process
communication technology that allows a computer program to cause a subroutine or procedure to
execute in another address space (commonly on another computer on a shared network) without the
programmer explicitly coding the details for this remote interaction. That is, the programmer would write
essentially the same code whether the subroutine is local to the executing program, or remote. When the
software in question is written using object- oriented principles, RPC may be referred to as remote
invocation or remote method invocation.
Note that there are many different (often incompatible) technologies commonly used to
accomplish is
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 85
Application Layer
BGP · DHCP · DNS · FTP · GTP · HTTP ·
IMAP · IRC · Megaco · MGCP ·
NNTP · NTP · POP · RIP · RPC ·
RTP · RTSP · SDP · SIP · SMTP
·
SNMP · SOAP · SSH · Telnet ·
TLS/SSL · XMPP · (more)
Transport Layer
TCP · UDP · DCCP · SCTP · RSVP · ECN ·
(more)
Internet Layer
IP (IPv4, IPv6) · ICMP · ICMPv6 · IGMP ·
IPsec · (more)
Link Layer
ARP/InARP · NDP · OSPF ·
Tunnels (L2TP) · PPP · Media Access
Control (Ethernet, DSL, ISDN, FDDI)
· (more)
The Internet Protocol Suite
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 86
ALGORITHM (valid for rpctime and rpc echoserver)
1. Write your own specification file “sample.x”
2. Use rpcgen to generate the files you need(i.e.,sample.h,sample_svc.c,and sample_clnt.c)
$rpcgen –a sample.x
3. Use rpcgen to generate sample server program
$rpcgen –Ss sample.x > sample_server.c
4. Use rpcgen to generate sample client program
$rpcgen –Sc sample.x > sample_client.c
5. Modify your sample server and sample client programs
6. Use cc to compile your server program(sample_server.c)
$cc sample_server.c sample_svc.c -o sample_server
7. Use cc to compile your client program(sample_client.c)
$cc sample_client.c sample_clnt.c -o sample_client
8. Run your server program
$./sample_server
Or to,put the server to run in the background
$./sample_server &
9. Run your client program
$./sample_client <ipaddress>
10. Use rpcinfo to manage your RPC resources,see the main page of rpcinfo for details.
(a)display rpc day time
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 87
Remote procedure call
List of files will be created from .x file
rpcdt_client rpcdt_client.c rpcdt_clnt.c rpcdt.h
rpcdt_server rpcdt_server.c rpcdt_svc.c rpcdt.x
step1:$ vi rpcdt.x
program TIME_PROG{
version TIME_VERSION{
string timeofday(void)=1;
}=1;
}=0x31234567;
[staff@cc5 cnlab]$ rpcgen -a rpcdt.x
/*This is sample code generated by rpcgen. * These are only templates and you can use them
* as a guideline for developing your own functions.*/
step2:
[staff@cc5 cnlab]$ vi rpcdt_server.c
#include "rpcdt.h"
char **
timeofday_1_svc(void *argp, struct svc_req *rqstp)
{
static char * result;
long t= time(NULL);
result=ctime(&t);
return &result;
}
[staff@cc5 cnlab]$ cc rpcdt_server.c rpcdt_svc.c -o rpcdt_server
rpcdt_server.c: In function `timeofday_1_svc':
rpcdt_server.c:15: warning: assignment makes pointer from integer without a cast
[staff@cc5 cnlab]$ ./rpcdt_server&
[3] 8218
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 88
Implementation of day time client using rpc
/*
* This is sample code generated by rpcgen.
* These are only templates and you can use them
* as a guideline for developing your own functions.
*/
#include "rpcdt.h"
void
rpcdt_prog_1(char *host)
{
CLIENT *clnt;
char * *result_1;
char *timeofday_1_arg;
#ifndef DEBUG
clnt = clnt_create (host, RPCDT_PROG, RPCDT_VERSION, "udp");
if (clnt == NULL) {
clnt_pcreateerror (host);
exit (1);
}
#endif /* DEBUG */
result_1 = timeofday_1((void*)&timeofday_1_arg, clnt);
if (result_1 == (char **) NULL) {
clnt_perror (clnt, "call failed");
}
printf("\n time of day service");
printf("\n today date and time is %s \n", result_1[0]);
#ifndef DEBUG
clnt_destroy (clnt);
#endif /* DEBUG */
}
int
main (int argc, char *argv[])
{
char *host;
if (argc < 2) {
printf ("usage: %s server_host\n", argv[0]);
exit (1);
}
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 89
host = argv[1];
rpcdt_prog_1 (host);
exit (0);
}
[staff@cc5 cnlab]$ cc rpcdt_client.c rpcdt_clnt.c -o rpcdt_client
[staff@cc5 cnlab]$ ./rpcdt_client 192.168.122.1
time of day service
today date and time is Sat Apr 17 12:59:48 2010
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 90
(b)Display rpc echo server
$ vi echo_prog.x
program ECGI_PROG{
version ECHO_VERSION{
string echo(string)=1;
}=1;
}=0x31234567;
$rpcgen –a echo_prog $vi echo_prog_server.c
/*
* This is sample code generated by rpcgen. * These are only templates and you can use them
* as a guideline for developing your own functions. */
#include "echo_prog.h"
#include<rpc/rpc.h>
char
**echo_1_svc(char
**argp, struct
svc_req *rqstp)
{
static char * result;
result=argp;
printf("\n server:%s\n",argp[0]);
// return ar;
return &result;
}
[staff@cc5 cnlab]$ cc echo_prog_server.c echo_prog_svc.c -o echo_prog_server
[staff@cc5 cnlab]$ ./echo_prog_server
server:hello
$vi echo_prog_client.c
/* sample code generated by rpcgen.
* These are only templates and you can use them
* as a guideline for developing your own functions.*/
#include <stdio.h>
#include "echo_prog.h"
#include <rpc/rpc.h>
void
ecgi_prog_1(char *host)
{
CLIENT *clnt;
//char * *result_1;
char * echo_1_arg;
char temp[100];
char *snd;
char *result;
#ifndef DEBUG
clnt = clnt_create (host, ECGI_PROG, ECHO_VERSION, "udp");
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 91
if (clnt == NULL) {
clnt_pcreateerror (host);
exit (0);
}
#endif /* DEBUG */
/* result_1 = echo_1(&echo_1_arg, clnt);
if (result_1 == (char **) NULL) {
clnt_perror (clnt, "call failed");
}*/
printf("enter a string");
scanf("%s",temp);
snd=&temp[0];
result=echo_1(&snd,clnt);
printf("the message was %s\n",*result);
#ifndef DEBUG
clnt_destroy (clnt);
#endif /* DEBUG */
}
int
main (int argc, char *argv[])
{
char *host;
if (argc!= 2) {
printf ("usage: %s server_host\n", argv[0]);
exit (0);
}
host = argv[1];
ecgi_prog_1 (host);
exit (1);
}
staff@cc5 cnlab]$ cc echo_prog_client.c echo_prog_clnt.c -o echo_prog_client
echo_prog_client.c: In function `ecgi_prog_1':
echo_prog_client.c:34: warning: assignment from incompatible pointer type
[staff@cc5 cnlab]$ ./echo_prog_client 192.168.122.1
enter a string hello
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 92
10. Implementation of Distance Vector Routing Protocol.
Distance Vector Algorithm –
1. A router transmits its distance vector to each of its neighbors in a routing packet.
2. Each router receives and saves the most recently received distance vector from each of its
neighbors.
3. A router recalculates its distance vector when:
• It receives a distance vector from a neighbor containing different information than before.
• It discovers that a link to a neighbor has gone down.
#include<stdio.h>
int dist[50][50],temp[50][50],n,i,j,k,x;
void dvr();
int main()
{
printf("\nEnter the number of nodes : ");
scanf("%d",&n);
printf("\nEnter the distance matrix :\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&dist[i][j]);
dist[i][i]=0;
temp[i][j]=j;
}
printf("\n");
}
dvr();
printf("enter value of i &j:");
scanf("%d",&i);
scanf("%d",&j);
printf("enter the new cost");
scanf("%d",&x);
dist[i][j]=x;
printf("After update\n\n");
dvr();
return 0;
}
void dvr()
{
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
for (k = 0; k < n; k++)
if (dist[i][k] + dist[k][j] < dist[i][j])
{
dist[i][j] = dist[i][k] + dist[k][j];
temp[i][j] = k;
}
for(i=0;i<n;i++)
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 93
{
printf("\n\nState value for router %d is \n",i+1);
for(j=0;j<n;j++)
printf("\t\nnode %d via %d Distance%d",j+1,temp[i][j]+1,dist[i][j]);
}
printf("\n\n");
}
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 94
11. Implementation of RSA public key algorithm.
Theory Cryptography has a long and colorful history. The message to be encrypted, known as the
plaintext, are transformed by a function that is parameterized by a key. The output of the encryption
process, known as the ciphertext, is then transmitted, often by messenger or radio. The enemy, or
intruder, hears and accurately copies down the complete ciphertext. However, unlike the intended
recipient, he does not know the decryption key and so cannot decrypt the ciphertext easily. The art of
breaking ciphers is called cryptanalysis the art of devising ciphers (cryptography) and breaking them
(cryptanalysis) is collectively known as cryptology.
There are several ways of classifying cryptographic algorithms. They are generally categorized based on
the number of keys that are employed for encryption and decryption, and further defined by their
application and use. The three types of algorithms are as follows:
1. Secret Key Cryptography (SKC): Uses a single key for both encryption and decryption. It is also
known as symmetric cryptography.
2. Public Key Cryptography (PKC): Uses one key for encryption and another for decryption. It is also
known as asymmetric cryptography.
3. Hash Functions: Uses a mathematical transformation to irreversibly "encrypt" information.
Public-key cryptography has been said to be the most significant new development in cryptography.
Modern PKC was first described publicly by Stanford University professor Martin Hellman and graduate
student Whitfield Diffie in 1976. Their paper described a two-key crypto system in which two parties
could engage in a secure communication over a non-secure communications channel without having to
share a secret key.
Generic PKC employs two keys that are mathematically related although knowledge of one key does not
allow someone to easily determine the other key. One key is used to encrypt the plaintext and the other
key is used to decrypt the ciphertext. The important point here is that it does not matter which key is
applied first, but that both keys are required for the process to work. Because pair of keys is required,
this approach is also called asymmetric cryptography.
In PKC, one of the keys is designated the public key and may be advertised as widely as the owner wants.
The other key is designated the private key and is never revealed to another party. It is straight forward
to send messages under this scheme.
The RSA algorithm is named after Ron Rivest, Adi Shamir and Len Adleman, who invented it in 1977.
The RSA algorithm can be used for both public key encryption and digital signatures. Its security is
based on the difficulty of factoring large integers.
Algorithm
1. Generate two large random primes, P and Q, of approximately equal size.
2. Compute N = P x Q
3. Compute Z = (P-1) x (Q-1).
4. Choose an integer E, 1 < E < Z, such that GCD (E, Z) = 1
5. Compute the secret exponent D, 1 < D < Z, such that E x D ≡ 1 (mod Z)
6. The public key is (N, E) and the private key is (N, D).
Note: The values of P, Q, and Z should also be kept secret. The message is encrypted using public key
and decrypted using private key.
An example of RSA encryption
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 95
1. Select primes P=11, Q=3.
2. N = P x Q = 11 x 3 = 33 Z = (P-1) x (Q-1) = 10 x 2 = 20
3. Lets choose E=3 Check GCD(E, P-1) = GCD(3, 10) = 1 (i.e. 3 and 10 have no common factors except
1), and check GCD(E, Q-1) = GCD(3, 2) = 1 therefore GCD(E, Z) = GCD(3, 20) = 1
4. Compute D such that E x D ≡ 1 (mod Z) compute D = E ^-1 mod Z = 3^-1 mod 20 find a value for D
such that Z divides ((E x D)-1) find D such that 20 divides 3D-1. Simple testing (D = 1, 2, ...) gives D = 7
Check: (E x D)-1 = 3.7 - 1 = 20, which is divisible by Z.
5. Public key = (N, E) = (33, 3) Private key = (N, D) = (33, 7).
Now say we want to encrypt the message m = 7, Cipher code = M ^E mod N
= 7^3 mod 33
= 343 mod 33
= 13.
Hence the ciphertext c = 13.
To check decryption we compute Message’ = C ^D mod N
= 13^7 mod 33
= 7.
Note that we don't have to calculate the full value of 13 to the power 7 here. We can make use of the fact
that a = bc mod n = (b mod n).(c mod n) mod n so we can break down a potentially large number into its
components and combine the results of easier, smaller calculations to calculate the final value One way of calculating m' is as follows:-
m' = 13^7 mod 33 = 13^(3+3+1) mod 33 = 13^3.13^3.13 mod 33
= (13^3 mod 33).(13^3 mod 33).(13 mod 33) mod 33
= (2197 mod 33).(2197 mod 33).(13 mod 33) mod 33
= 19.19.13 mod 33 = 4693 mod 33
= 7.
Now if we calculate the cipher text c for all the possible values of m (0 to 32), we get
m 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
c 0 1 8 27 31 26 18 13 17 3 10 11 12 19 5 9 4
m 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
c 29 24 28 14 21 22 23 30 16 20 15 7 2 6 25 32
Note that all 33 values of m (0 to 32) map to a unique code c in the same range in a sort of random manner.
In this case we have nine values of m that map to the same value of c - these are known as unconcealed
messages. m = 0 and 1 will always do this for any N, no matter how large. But in practice, higher values
shouldn't be a problem when we use large values for N.
If we wanted to use this system to keep secrets, we could let A=2, B=3, ..., Z=27. (We specifically avoid
0 and 1 here for the reason given above). Thus the plaintext message "HELLOWORLD" would be
represented by the set of integers m1, m2, ...
{9,6,13,13,16,24,16,19,13,5} Using our table above, we obtain ciphertext integers c1, c2, ...
{3,18,19,19,4,30,4,28,19,26}
Note that this example is no more secure than using a simple Caesar substitution cipher, but it serves to
illustrate a simple example of the mechanics of RSA encryption.
Remember that calculating m^e mod n is easy, but calculating the inverse c^-e mod n is very difficult,
well, for large n's anyway. However, if we can factor n into its prime factors p and q, the solution becomes
easy again, even for large n's. Obviously, if we can get hold of the secret exponent d, the solution is easy,
too.
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 96
Key Generation Algorithm
1. Generate two large random primes, p and q, of approximately equal size such that their product n = pq
is of the required bit length, e.g. 1024 bits. [See note 1].
2. Compute n = pq and (φ) phi = (p-1)(q-1).
3. Choose an integer e, 1 < e < phi, such that gcd(e, phi) = 1. [See note 2].
4. Compute the secret exponent d, 1 < d < phi, such that ed ≡ 1 (mod phi). [See note 3].
5. The public key is (n, e) and the private key is (n, d).
The values of p, q, and phi should also be kept secret.
• n is known as the modulus.
• e is known as the public exponent or encryption exponent.
• d is known as the secret exponent or decryption exponent.
Encryption
Sender A does the following:-
1. Obtains the recipient B's public key (n, e).
2. Represents the plaintext message as a positive integer m.
3. Computes the ciphertext c = m^e mod n.
4. Sends the ciphertext c to B.
Decryption
Recipient B does the following:
1. Uses his private key (n, d) to compute m = c^d mod n.
2. Extracts the plaintext from the integer representative m.
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 97
Source code
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<string.h>
long int gcd(long int a,long int b)
{
if(a==0)
return b;
if(b==0)
return a;
return gcd(b,a%b);
}
long int isprime(long int a)
{
int i;
for(i=2;i<a;i++)
if((a%i)==0)
return 0;
return 1;
}
long int encrypt(char ch,long int n, long int e)
{
int i;
long int temp=ch;
for(i=1;i<e;i++)
temp=(temp *ch)%n;
return temp;
}
char decrypt(long int ch,long int n,long int d)
{
int i;
long int temp=ch;
for(i=1;i<d;i++)
ch=(temp *ch)%n;
return ch;
}
int main()
{
long int i,len;
long int p,q,n,phi,e,d,cipher[50];
char text[i];
printf("enter the text to be encrypted\n");
scanf("%s",&text);
len=strlen(text);
do
{
p=rand()%30;
}while(!isprime(p));
do
{
q=rand()%30;
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 98
}while(!isprime(q));
n=p*q;
phi=(p-1)*(q-1);
do{
e=rand()%phi;
}while(gcd(phi,e)!=1);
do{
d=rand()%phi;
}while(((d*e)%phi)!=1);
printf("two prime no P and Q are %d & %d \n",p,q);
printf("n(p-q)=%d * %d =%d\n",p,q,p*q);
printf("p-1)*(q-1)=%d\n",phi);
printf("public key(n,e):%d,%d\n",n,e);
printf("private key are:%d,%d\n",n,d);
for(i=0;i<len;i++)
cipher[i]=encrypt(text[i],n,e);
printf("encrypted message\n");
for(i=0;i<len;i++)
printf("%d\n",cipher[i]);
for(i=0;i<len;i++)
text[i]=decrypt(cipher[i],n,d);
printf("\n");
printf("decrypted message\n");
for(i=0;i<len;i++)
printf("%c",text[i]);
printf("\n");
return 0;
}
COMPUTER NETWORKS LAB IT Dept DCET
MS. RESHMA BEGUM Page 99
Viva Questions
1. What are functions of different layers?
2. Differentiate between TCP/IP Layers and OSI Layers
3. Why header is required?
4. What is the use of adding header and trailer to frames?
5. What is fragmentation?
6. Difference between IPv4 and IPv6.
7. Differentiate between flow control and congestion control.
8. Differentiate between Point-to-Point Connection and End-to-End connections.
9. What are protocols running in different layers?
10. Differentiate between TCP and UDP.
11. Differentiate between Connectionless and connection oriented connection.
12. What is meant by subnet?
13. What is meant by Gateway?
14. What is an IP address?
15. What is MAC address?
16. Why IP address is required when we have MAC address?
17. What is meant by port?
18. What are ephemerical port number and well known port numbers?
19. What is traceroute?
20. What is whois?
21. What is a socket?
22. What are the parameters of socket()?
23. Describe bind(), listen(), accept(),connect(), send() and recv().
24. What are system calls? Mention few of them.
25. How do you classify congestion control algorithms?
26. Differentiate between Leaky bucket and Token bucket.
27. How do you implement Leaky bucket?
28. What are the other error detection algorithms?
29. What are Routing algorithms?
30. How do you classify routing algorithms? Give examples for each.
31. What are drawbacks in distance vector algorithm?
32. How routers update distances to each of its neighbor? 33. Difference between Static and Dynamic web page. 34. What is VOIP?
35. Define Cryptography. 36. What are Digital Signatures? 37. What are authentication Protocols? 38. What is Email Security? 39. Define SSL in web security.
40. Difference between Public key and private key algorithms.