Sie sind auf Seite 1von 77

STUDY OF HEADER FILES

1.

stdio.h:
Has standard input and output library providing simple and efficient buffered stream IO
interface.

2.

unistd.h:
It is a POSIX standard for open system interface.

3.

string.h:
This header file is used to perform string manipulation operations o
n NULL terminated strings.

4.

stdlib.h:
This header file contains the utility functions such as string conversion routines, memory
allocation routines, random number generator, etc.

5.

sys/types.h:
Defines the data type of socket address structure in unsigned long.

6.

sys/socket.h:
The socket functions can be defined as taking pointers to the generic socket address structure
called sockaddr.

7.

netinet/in.h:
Defines the IPv4 socket address structure commonly called Internet socket address structure
called sockaddr_in.

8.

netdb.h:
Defines the structure hostent for using the system call gethostbyname to get the network host
entry.

9.

time.h:
Has structures and functions to get the system date and time and to perform time manipulation
functions. We use the function ctime(), that is defined in this header file , to calculate the current
date and time.

10.

sys/stat.h:
Contains the structure stat to test a descriptor to see if it is of a specified type. Also it is used to
display file or file system status.
1

11.

sys/ioctl.h:
Macros and defines used in specifying an ioctl request are located in this header file. We use the
function ioctl() that is defined in this header file. ioctl() function is used to perform ARP cache
operations.

12.

pcap.h:
Has function definitions that are required for packet capturing. Some of the functions are
pcap_lookupdev(),pcap_open_live() and pcap_loop(). pcap_lookupdev() is used to initialize the
network device.The device to be sniffed is opened using the pcap_open_live(). Pcap_loop()
determines the number of packets to be sniffed.

13.

net/if_arp.h:
Contains the definitions for Address Resolution Protocol. We use this to manipulate the ARP
request structure and its data members arp_pa,arp_dev and arp_ha. The arp_ha structures data
member sa_data[ ] has the hardware address.

14.

errno.h:
It sets an error number when an error and that error can be displayed using perror function. It has
symbolic error names. The error number is never set to zero by any library function.

15.

arpa/inet.h:
This is used to convert internet addresses between ASCII strings and network byte ordered
binary values (values that are stored in socket address structures). It is used for inet_aton,
inet_addr, inet_ntoa functions.

IMPLEMENTATION OF SLIDING WINDOW PROTOCOL


2

Ex. No: 1
AIM: To write a program to simulate Sliding Window Protocol.
METHODOLOGY:
Sliding Window Protocol:
Sliding Window Protocols are a feature of packet-based data transmission protocols. They
are used in the data link layer (OSI model) as well as in TCP (transport layer of the OSI model).
They are used to keep a record of the frame sequences sent, and their respective acknowledgements
received, by both the users. In transmit flow control, sliding window is a variable-duration window
that allows a sender to transmit a specified number of data units before an acknowledgment is
received or before a specified event occurs.
The sender creates a sequence number for each frame as it is transmitted. Throughout the
communication, it maintains the send window size, the last acknowledgment received, and the last
frame sent. To ensure that the window does not overflow, the sender ensures that the window size is
greater than the sequence number of last frame sent minus the sequence number last
acknowledgment received.

Sender's data link layer maintains a 'sending window' which consists of a set of
sequence numbers corresponding to the frames it is permitted to send.

Similarly, the receiver maintains a 'receiving window' corresponding to the set of


frames it is permitted to accept.

The sequence numbers within the sender's window represent the frames sent but as
yet not acknowledged.

Whenever a new packet arrives from the network layer, the upper edge of the
window is advanced by one.

When an acknowledgement arrives from the receiver the lower edge is advanced by
one. The receiver's window corresponds to the frames that the receiver's data link
layer may accept.

When a frame with sequence number equal to the lower edge of the window is
received, an acknowledgement is generated and the window is rotated by one.

When a frame falling outside the window is received, the receiver's data link layer
may either discard this frame or it may accept these frames and buffer them until the
appropriate frame is received.

Algorithm:
Server:
1. Start the program.
2. Create the socket, establish a connection using accept function.
3. Decide the Offered window size R based on the minimum value of Congestion window and
advertised window.
4. Send R bytes of data to receiver.
5. Receive the acknowledgement from the receiver.
6. Receive the Window update value based on it transmit the data until Zero window arrives.
Client:
1. Start the program.
2. Create the socket and Connect to the server using connect() function.
3. Send the advertised window size to the server.
4. Receive the data.
5. Send the acknowledgement of next data to be received to the server.
6. Calculate the window update and send it as the current window size for sending data.

Sliding Window Server:


#include<stdio.h>
4

#include<string.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<unistd.h>
#include<stdlib.h>
#define SIZE 4
int main()
{
int sid,bd,lis,accpt,i,j,status,length;
struct sockaddr_in sin;
char str[20],frame[20],temp[20],ack[20];
socklen_t len;
sid=socket(PF_INET,SOCK_STREAM,0);
if(sid == -1)
{
printf("\n Error in creating socket \n");
exit(-1);
}
printf("\n The socket is created successfully");
memset(&sin,0,sizeof(sin));
sin.sin_family=AF_INET;
sin.sin_port=htons(4050);
sin.sin_addr.s_addr=htonl(INADDR_ANY);
bd=bind(sid,(struct sockaddr*)&sin,sizeof(sin));
if(bd < 0)
{
printf("\n Binding failed \n");
exit(-1);
}
printf("\n Binding Completed");
lis=listen(sid,5);
5

if(lis < 0)
{
printf("\n Error in listening \n");
exit(-1);
}
printf("\n Listening is completed");
len=sizeof(sin);
accpt=accept(sid,(struct sockaddr*)&sin,&len);
if(accpt < 0)
{
printf("\n Error in Accepting \n");
exit(-1);
}
printf("\n Client is Accepted \n");
printf("\n Enter the text: ");
scanf("%s",str);
i=0;
while(i < strlen(str))
{
strncpy(frame,str+i,SIZE);
frame[i+SIZE]='\0';
printf("\n Transmitting Frames: ");
length=strlen(frame);
for(j=0;j<length;j++)
printf("%d",i+j);
write(accpt,frame,sizeof(frame));
read(accpt,ack,20);
sscanf(ack,"%d",&status);
if(status==-1)
printf("\n Transmission is successful \n");
else
{
printf("\n Received error in Frame: %d \n",status);
6

printf("\n Retansmitting Frames: ");


for(j=0;;)
{
frame[j]=str[j+status];
j++;
printf("%d",j+status);
if((j+status)%4==0)
break;
}
frame[j]='\0';
write(accpt,frame,sizeof(frame));
}
i+=SIZE;
}
write(accpt,"exit",sizeof("exit"));
shutdown(sid,2);
close(sid);
}
Client:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
int main()
{
int sid,con,choice;
struct sockaddr_in sin;
char str[20],err[20];
sid=socket(PF_INET,SOCK_STREAM,0);
if(sid == -1)
{
7

printf("\n Error in creating the socket \n");


exit(-1);
}
printf("\n Socket created successfully");
memset(&sin,0,sizeof(sin));
sin.sin_family=AF_INET;
sin.sin_port=htons(4050);
sin.sin_addr.s_addr=htonl(INADDR_ANY);
con=connect(sid,(struct sockaddr*)&sin,sizeof(sin));
if(con < 0)
{
printf("\n The connection established falied \n");
exit(-1);
}
printf("\n Connection established successfully \n");
for(;;)
{
read(sid,str,20);
if(!strcasecmp(str,"exit"))
break;
printf("\n Received: %s ",str);
printf(" \n Do u want to report an error(1-Yes 0- no): ");
scanf("%d",&choice);
if(!choice)
write(sid,"-1",sizeof("-1"));
else
{
printf(" Enter the sequence no of the frame where error has occurred: ");
scanf("%s",err);
write(sid,err,sizeof(err));
read(sid,str,20);
printf("\n Received the re-transmitted frames: %s",str);
}
8

}
shutdown(sid,2);
close(sid);
}
Output
[test@ritlinux ~]$ cc slwserver.c
[test@ritlinux ~]$ ./a.out
The socket is created successfully
Binding Completed
Listening is completed
Client is Accepted
Enter the text: computernetworks
Transmitting Frames: 0123
Transmission is successful
Transmitting Frames: 4567
Received error in Frame: 5
Retansmitting Frames: 678
Transmitting Frames: 891011
Transmission is successful
Transmitting Frames: 12131415
Transmission is successful
[test@ritlinux ~]$ cc slwclient.c
[test@ritlinux ~]$ ./a.out
-- INSERT -Socket created successfully
Connection established successfully
-- INSERT -Received: comp
Do u want to report an error(1-Yes 0- no): 0
-- INSERT -Received: uter
Do u want to report an error(1-Yes 0- no): 1
Enter the sequence no of the frame where error has occurred:5
9

-- INSERT -Received the re-transmitted frames: ter


Received: netw
Do u want to report an error(1-Yes 0- no): 0
-- INSERT -Received: orks
Do u want to report an error(1-Yes 0- no): 0
[test@ritlinux ~]$

Result:
Thus the program to simulate sliding window protocol was done and output was verified.

10

STUDY OF SOCKET PROGRAMMING AND CLIENT SERVER MODEL


Ex. No: 2
DATE:
1. Socket Interface
# It is based on UNIX and defines a set of system calls (procedures) that are an extension of
system calls used to access files.
# A "socket" is a loose term used to describe "an end point for communication." The traditional
Berkley Socket API is a set of C function calls used to support network communication
2. Primary Socket Calls
socket()- create a new socket and return its descriptor
bind()- associate a socket with a port and address
listen()- establish queue for connection requests
accept()- accept a connection request
connect()- initiate a connection to a remote host
recv()- receive data from a socket descriptor
send()- send data to a socket descriptor
close()- one-way close of a socket descriptor
3. Network Database Administration functions
gethostbyname - given a hostname, returns a structure which specifies its DNS name(s) and
IP address(es)
getservbyname - given service name and protocol, returns a structure which specifies its
name(s) and its port address
gethostname - returns hostname of local host
getservbyname getservbyport getservent
getprotobyname ,getprotobynumber ,getprotobyent
getnetbyname ,getnetbyaddr, getnetent
4. Socket Utility Functions
ntohs /ntohl - convert short/long from network byte order (big endian to host byte order )
htons /htonl - convert short/long from host byte order to network byte order
inet_ntoa /inet_addr - convert 32-bit IP address (network byte order to/from a dotted
decimal string)
perror () - print error message (based on errno) to stderr
herror () - print error message for gethostbyname () to stderr (used with DNS)
5. Primary Header Files
- In Unix:
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <time.h>
#include <netinet/in.h>
#include <arpa/inet.h>

/* basic system data types */


/* basic socket definitions */
/* timeval{} for select() */
/* timespec{} for pselect() */
/* sockaddr_in{} and other Internet defns */
/* inet(3) functions */
11

#include <errno.h>
#include <fcntl.h> /* for nonblocking, on windows don't use fnctl(), use ioctlsocket() */
#include <netdb.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
/* for S_xxx file mode constants */
#include <unistd.h>
/* this file is typically only for Linux *nix OS's */
#include <sys/wait.h>
#include <sys/un.h>
/* for Unix domain sockets */
#include <stdarg.h>
/* for sdprintf */
- In Windows
#include <windows.h>
#include <sys/types.h>
#include <winsock.h>
Connections and Associations
In Socket terms a connections between two processes in called an association. An association can be
abstractly defined as a 5- tuple which specifies the two processes and a method of communication.
For example:
{protocol, local-addr, local-process, foreign-addr, foreign-process}
A half-association is a single side of an association (a 3- tuple)
{protocol, addr, process}
Networking Terms

packet - the smallest unit that can be transferred through the network by itself
protocol - a set of rules and conventions between the communicating participants
A collection of protocol layers is referred to as a protocol suite, protocol family or
protocol stack. TCP/IP is one such protocol suite.

6 .Basic Socket Calls & Their prototypes


Procedures that implement the Socket API
6.1. The Socket Procedure:
The socket procedure creates a socket and returns an integer descriptor. This
descriptor is used by the application to be passed as an argument to call procedures to transfer data
across the network.

Initialize a socket or create a socket


FORMAT: int sockfd = socket(int family, int type, int protocol)
Returns a socket descriptor if successful;-1 if error
12

where:
family stands for addressing family.
symbolic name
Protocol Family

AF_UNIX

intra-host UNIX

AF_INET

TCP/IP[default]

AF_NS

Xerox NS

AF_DECNET

DEC DNA

Its purpose is to specify the method of addressing used by the socket.


o

type stands for the type of socket interface to be used.


service type
symbolic name
comment
datagram

SOCK_DGRAM

UDP protocol in AF_INET

reliable, in-order

SOCK_STREAM

TCP protocol in AF_INET

raw socket

SOCK_RAW

direct access to network layer

protocol can be UDP, TCP, IP or ICMP.

sockfd is an integer (similar to a file descriptor) returned by the socket call. This is
the Socket Descriptor, which uniquely defines the created socket if the creation is
Successful. It returns 1 if there is an error. The Socket Descriptor is used by other
functions to refer the socket.

Example:
if (( sockfd = socket(AF_INET,SOCK_STREAM,0)) == -1)
{ printf(": error opening socket");
exit(-1);
}
Example:
if ( (sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
{ /* handle error */ }

// TCP

// UDP

6.2 The Bind Procedure: Bind (Register) a socket to a port address.


The Bind Function binds a socket to a local socket address by adding the local socket address to
an already created socket. When Created a socket has neither a local address nor a remote
address. A Server uses the bind procedure to supply a protocol port number at which the server
will wait for contact. The Prototype is given as
FORMAT:

int bind(int sockfd, struct sockaddr *localaddr, int addrlen)


Returns 0 if successful;-1 if error

where:
13

o
o

sockfd is the same integer returned by the socket call.


localaddr is the local address returned by the bind call. [ i.e. ] *localaddr is a pointer
to the struct sockaddr which is used in the bind call

socklen_t localaddrlen is an interger returning the size of the struct sockaddr which
can be obtained by the call sizeof(struct sockaddr)

Example:
if ( bind(sock, (struct sockaddr *) &sock_addr, sizeof(sock_addr)) < 0)
{
printf(": error binding socket to local address");
exit(-1);
}
6.3 The LISTEN Procedure: Indicate readiness to receive connections
The listen function is called only by the server. It creates a passive socket from an
unconnected socket. Before calling the listen function, the socket must already be created and the
local socket address fields set. This function informs the OS that the server is ready to accept the
connection through this socket. To do so, a server calls the listen procedure whose prototype is as
follows:
FORMAT:

int listen(int sockfd, int queue-size)


Returns 0 if successful;-1 if error

where:
o
o

sockfd is the same integer returned by the socket call.


queue-size indicates the number of connection requests which can be queued by the
system while the local process has not yet issued the accept call.

6.4 The Accept Procedure: Accept a connection


The accept function is called by a TCP Server to remove the first connection request from
the corresponding queue. If there are no requests (the queue is empty), the accept function is
put to sleep. The prototype is given as
FORMAT: int accept(int sockfd, struct sockaddr *foreign-address, int addrlen)
Returns a socket descriptor if successful;-1 if error
where:
o
o

sockfd is the same integer returned by the socket call.


foreign-address is the pointer to the address of the foreign (client) process that has
requested the connection returned by the accept call.

Addrlen is the length of the client address.

Note that this accept call is issued by a server process rather than a client process. If there is
a connection request waiting on the queue for this socket connection, accept takes the first
request on the queue and creates another socket with the same properties as sockfd; This
function actually creates a new socket (child socket) that can be used by a child server to
14

connect to the client. Otherwise, accept will block the caller process until a connection
request arrives. The return value of this function is the new socket descriptor
6.5 The Connect procedure: Request connection to the server
The connect function is used by a process ( usually a client) to establish an active connection
to a remote process (server).The prototype is as follows
FORMAT: int connect(int sockfd, struct sockaddr *foreign-address, int addrlen)
Returns 0 if successful;-1 if error
where:
o
o

sockfd is the same integer returned by the socket call.


foreign-address is the address of foreign (server) process returned by the connect
call.

addrlen is the length of that server address

Note that this call is issued by a client process rather than a server process.
Example:
if (connect(sock, ( struct sockaddr *) &sock_addr, sizeof sock_addr) == -1)
{
printf(": socket connection error");
exit(-1);
}
6.6 Close a socket:
FORMAT:

int close(int sockfd)


Returns 0 if successful;-1 if error

where:
sockfd is the same integer returned by the socket call.
Example:
/* connected socket is int sockt */
close( sockt ); /* close socket imeediately */
shutdown( sockt, 0); /* close socket, and dont recieve any more */
shutdown( sockt, 1);
/* close socket, and dont send any more */
shutdown( sockt, 2);/* close socket, and dont recieve, or send any more */
6.7 Send and/or receive data

int read(int sockfd, char *buf, unsign int nbytes)


int write(int sockfd, char *buf, unsign int nbytes)

readv(sockfd, char *buffer, int addrlen),

recv(),

readfrom(),
15

send(sockfd, msg, len, flags),

int recvfrom(int sockfd, char *buf, int nbytes, int flags, struct sockaddr
*from, int addrlen)

int sendto(int sockfd, char *buf, int nbytes, int flags, struct sockaddr *to, int
addrlen)

read() & write () are used for connection oriented Transport

recvfrom() and sendto() are used for connection less Transport

Examples:
1. if (write(sock, message, size) <0 )
{
printf(": error writing to remote host");
exit(-1);
}
2 .bytes_received = read(sock, reply, sizeof(reply));
These calls can be used to receive and send data in an established socket association
(or connection). Note that these calls are similar to the standard read and write file I/O
system calls.

data sent/received using standard UNIX i/o system calls or network-specific system calls
system call

device

buffering

read()/write()

any i/o

single

readv()/writev()

any i/o

scatter/gather

recv()/send()

socket

single

recvfrom()/sendto()

socket

single

recvmsg()/sendmsg()

socket

scatter/gather

Sending via a socket: sendto() -Connectionless


int sendto (int sockfd, char *buff, int bufflen, int flags, struct sockaddr *toaddrptr, int addresslen)
sockfd is the variable assigned socket() return value.
*buff is a set of consecutive mem. locs. holding message to send

bufflen is number of bytes to send

flags can be used to specify options. Always 0 for us.


16

*toaddrptr is address of sockaddr_in structure holding destination address info. Must be cast
to type sockaddr.

addresslen is the size of the address structure

OK return code does NOT imply data correctly delivered, only correctly sent

Reading/Writing Sockets: examples


Example: using sendto()
char buffer[50];
struct sockaddr_in other_app_addr;
int retcode

/* suppose we have done socket() and


bind() calls, filled in
other_app_addr,and put
23 bytes of data into buffer */
retcode = sendto(sockfd, buffer, 23, 0,
(struct sockaddr *) &other_app_addr,
sizeof(other_app_addr))
Reading from a socket: recvfrom() -Connectionless

Example: using recvfrom()


char buffer[50];
struct sockaddr_in other_app_addr;
int nread, addrlen;
/* suppose we have done socket(),
bind() */
nread = recvfrom(sockfd, buffer,
23, 0,
(struct sockaddr *)
&other_app_addr, &addrlen))

int recvfrom (int sockfd, char *buff, int bufflen, int flags, struct sockaddr *fromaddrptr,
int *addresslen)

sockfd is variable assigned socket() return value.


*buff is a set of consecutive mem. locs. into which received data to be written

bufflen is number of bytes to read

flags can be used to specify options. Always 0 for us.

*fromaddrptr is address of sockaddr_in structure containing address info of socket that


sent this data. A returned value.

addresslen is size of address structure. A returned value.

recvfrom() returns number bytes actually received


Sending Data through send()
To send data over a socket the program will need to make a call to send (); if the socket is nonblocking the send call should return immediately with the number of bytes that were successfully
written to the sockets output queue. The return from send does not indicate the number of bytes
received on the other end of the connection nor does it indicate how large the TCP packet size is.
But if you get a positive return value on a send call it means the OS has taken responsibility for
transmitting that data
Example:
int i;
17

/* sockd is the connected socket file descriptor */


i = send( sockd, "Hello World!\n", 13, 0);
if( i > 0 ){
printf("sent %d bytes\n", i);
}
Receiving Data through recv()
To receive data over a socket the program will need to make a call to recv(); if the socket is nonblocking the recv call should return immediately with the number of bytes that were successfully
read from the sockets input queue. The return from recv does not indicate the number of bytes sent
by the remote host, nor does it indicate how large the tcp packet size was that was read. It is also
important to note that if recv() returns 0 ( zero ) that indicates the remote socket has closed the
connection.
Byte Ordering Routines
Byte ordering routines: convert to/from host 16- and 32-bit integers from/to ``network byte
order''
o Different computers may store bytes of integer in different order in memory.
o

internal representation of 2^{24}

network byte order is big-endian

Integer quantities (such as addressing info) should be explicitly converted to/from


network byte order (nbo).

Function
name

action

htonl

convert 32-bit host format to Network byte


order

ntohl

convert Network byte order to 32-bit host


18

format
htons

convert 16-bit host format to Network byte


order

ntos

convert Network byte order to 16-bit host


format

Declarations for byte-order transformations

u_short htons (u_short host_short)


u_short ntohs (u_short network_short)
u_long htonl (u_long host_short)
u_long ntohl (u_long network_short)

An Example Scenario
As an example, consider the socket system calls for a connection-oriented protocol.

19

RESULT:
Thus the basic functions used for Socket Programming was studied successfully.
SIMULATING ARP /RARP PROTOCOLS
Ex. No: 3
DATE:
AIM: To implement ARP and RARP protocol
20

Address Resolution Protocol (ARP) is a protocol for mapping an Internet Protocol address (IP
address) to a physical machine address that is recognized in the local network. For example, in
IP Version 4, the most common level of IP in use today, an address is 32 bits long. In an
Ethernet local area network, however, addresses for attached devices are 48 bits long. (The
physical machine address is also known as a Media Access Control or MAC address.) A table,
usually called the ARP cache, is used to maintain a correlation between each MAC address
and its corresponding IP address. ARP provides the protocol rules for making this correlation
and providing address conversion in both directions.
How ARP Works
When an incoming packet destined for a host machine on a particular local area network
arrives at a gateway, the gateway asks the ARP program to find a physical host or MAC
address that matches the IP address. The ARP program looks in the ARP cache and, if it finds
the address, provides it so that the packet can be converted to the right packet length and
format and sent to the machine. If no entry is found for the IP address, ARP broadcasts a
request packet in a special format to all the machines on the LAN to see if one machine knows
that it has that IP address associated with it. A machine that recognizes the IP address as its
own returns a reply so indicating. ARP updates the ARP cache for future reference and then
sends the packet to the MAC address that replied
ADDRESS RESOLUTION PROTOCOL
#include<unistd.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<stdio.h>
#include<string.h>
#include<sys/socket.h>
int main()
{
int sd,j=0,port=2000;
char con[50]="0";
struct sockaddr_in ser;
char ip[50][50]={"121.0.0.1","121.0.0.2","121.0.0.3","121.0.0.4"};
char eth[50][50]={"121.32.45.0.0.1","121.32.45.0.0.2","121.32.45.0.0.3","121.32.45.0.0.4"};
sd=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
bzero((char*)&ser,sizeof(ser));
ser.sin_family=AF_INET;
ser.sin_port=htons(port);
ser.sin_addr.s_addr=htonl(INADDR_ANY);
printf("Enter the ip address:");
scanf("%s",&con);
for(j=0;j<4;j++)
{
if(strcmp(con,ip[j])==0)
21

{
printf("Ethernet Address is:%s\n",eth[j]);
break;
}
}
return 0;
}
OUTPUT:
Enter the ip address:121.0.0.1
Ethernet Address is:121.32.45.0.0.1
REVERSE ADDRESS RESOLUTION PROTOCOL
#include<unistd.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<string.h>
#include<sys/socket.h>
#include<stdio.h>
int main()
{
int sd,j=0,port=2000;
char con[50]="0";
struct sockaddr_in ser;
char ip[50][50]={"121.0.0.1","121.0.0.2","121.0.0.3","121.0.0.4"};
char eth[50][50]={"121.32.45.0.0.1","121.32.45.0.0.2","121.32.45.0.0.3","121.32.45.0.0.4"} ;
sd=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
bzero((char*)&ser,sizeof(ser));
ser.sin_family=AF_INET;
ser.sin_port=htons(port);
ser.sin_addr.s_addr=htonl(INADDR_ANY);
printf("Enter the Ethernet address:");
scanf("%s",&con);
for(j=0;j<4;j++)
{
if(strcmp(con,eth[j])==0)
{
printf("IP Address is:%s\n",ip[j]);
break;
}
}
return 0;
}

OUTPUT:
22

Enter the Ethernet address:121.32.45.0.0.1


IP Address is:121.0.0.1

RESULT:
Thus the ARP and RARP was implement successfully.

SIMULATING PING AND TRACEROUTE COMMANDS


Ex. No: 4
DATE:
PINGSERVER:
#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<unistd.h>
#include<netinet/in.h>
#include<string.h>
intmain(intargc,char**argv)
{
intsock,chat=0;
structsockaddr_inadd,addr;
bzero(&add,sizeof(add));
add.sin_family=AF_INET;
add.sin_addr.s_addr=htons(INADDR_ANY);
add.sin_port=htons(5478);
sock=socket(AF_INET,SOCK_STREAM,0);
intb=bind(sock,(structsockaddr*)&add,sizeof(add));
if(b<0)
perror("nobind");
else
perror("bind");
intlis=listen(sock,3);
intnsd,addrlen;
addrlen=sizeof(addr);
nsd=accept(sock,(structsockaddr*)&addr,&addrlen);
printf("%d",nsd);
if(nsd<0)
perror("noaccept");
else
printf("connected,%d",nsd);
intstr,buf_size=1024;
23

char*buffer="Thisisthetestmessage";
ints,ii=0;
while(ii!=3)
{
s=send(nsd,buffer,buf_size,0);
if(s<0)
perror("send");
ii++;
}
close(sock);
close(b);
close(nsd);
}
OUTPUT:
[sivait@localhost~]$ccpingser.c
[sivait@localhost~]$./a.out
bind:Success
4connected,4[sivait@localhost~]$
PINGCLIENT:
#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<unistd.h>
#include<netinet/in.h>
#include<string.h>
#include<arpa/inet.h>
intmain(intargc,char**argv)
{
intsock,i=10,r,s,buf_size=1024;
structsockaddr_inadd;
intc=0;
bzero(&add,sizeof(add));
add.sin_family=AF_INET;
add.sin_addr.s_addr=htonl(INADDR_ANY);
add.sin_port=htons(5478);
sock=socket(AF_INET,SOCK_STREAM,0);
intcon=connect(sock,(structsockaddr*)&add,sizeof(add));
if(con<0)
perror("networkisunreachable");
charbuffer[buf_size],buf[1024];
while(c!=4)
{
r=recv(sock,buf,buf_size,0);
if(r<0)
24

{
perror("requestistimedout");
printf("packetsend=4;received=0;loss=100");
}
else
{
printf("replayfrom%s",inet_ntoa(add.sin_addr));
printf("icmp_seq=%d:",i);
printf("tt1=64\n");
i++;
c++;
}
}
printf("packetsend=4;received=4;loss=0");
close(sock);
}
OUTPUT:
Server:
[test@ritlinux~]$./a.out
bind:Success
4connected,4[test@ritlinux~]$
Client:
[test@ritlinux~]$ccpingcli.c
[test@ritlinux~]$./a.out
replayfrom0.0.0.0icmp_seq=10:tt1=64
replayfrom0.0.0.0icmp_seq=11:tt1=64
replayfrom0.0.0.0icmp_seq=12:tt1=64
replayfrom0.0.0.0icmp_seq=13:tt1=64
packetsend=4;received=4;loss=0[test@ritlinux~]$

25

5. SOCKET FOR HTTP FOR WEB PAGE UPLOAD AND DOWNLOAD


Ex. No: 5.1

IMPLEMENTATION OF HTTP
AIM:
To write a program for implementing HTTP.
METHODOLOGY:
HTTP:
Hypertext Transfer Protocol (HTTP) is an application-level protocol for distributed,
collaborative, hypermedia information systems. [1] Its use for retrieving inter-linked resources, called
hypertext documents. There are two major versions, HTTP/1.0 that uses a separate connection for
every document and HTTP/1.1 that can reuse the same connection to download, for the just served
page. Hence HTTP/1.1 may be faster as it takes time to set up such connections.

HTTP is a request/response standard as is typical in client-server computing. The client is an


application (e.g. web browser, spider etc) on the computer used by an end-user, the server is an
26

application running on the computer hosting the web site. The clientwhich submits HTTP requests
is also referred to as the user agent. The responding serverwhich stores or creates resources
such as HTML files and imagesmay be called the origin server.
Algorithm:
Server:
1. Start the program.
2. Create the socket and accept the connection from the client.
Client:
1. Start the program.
2. Create the socket and Connect to the server using connect() function.
3. Send the file name the get request to the server

HTTP SERVER
#include<stdio.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<string.h>
int main()
{
FILE *f;
int sd,len,i=0,l,s,sd1,si,eof;
struct sockaddr_in ser;
struct sockaddr_in cli;
char buf[50],msg[50],rmsg[50];
if((sd=socket(AF_INET,SOCK_STREAM,0))<0)
{
printf("Error");
return 0;
}
bzero(&ser,sizeof(ser));
27

ser.sin_family=AF_INET;
ser.sin_port=htons(7879);
ser.sin_addr.s_addr=htonl(INADDR_ANY);
if((bind(sd,(struct sockaddr*)&ser,sizeof(ser)))<0)
{
printf("Binding error");
return 0;
}
if((listen(sd,5))<0)
{
printf("Listening error");
return 0;
}
si=sizeof(cli);
if((sd1=accept(sd,(struct sockaddr*)&cli,&si))<0)
{
printf("Accepting error");
return 0;
}
recv(sd1,msg,50,0);
printf("\nThe File Name Is %s\n",msg);
f=fopen(msg,"r");
do
{
bzero(&buf,50);
fread(&buf,50,1,f);
send(sd1,buf,50,0);
//getchar();
}while(!feof(f));
send(sd1,"COMPLETED",20,0);
fclose(f);
close(sd1);
}
28

HTPP CLIENT
#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<string.h>
main()
{
FILE *fp;
int sd,i=0,len,eof;
struct sockaddr_in ser;
char buf[50],rmsg[50],source[15],dest[15];
if((sd=socket(AF_INET,SOCK_STREAM,0))<0)
{
printf("Error on Socket creation");
return 0;
}
bzero(&ser,sizeof(ser));
ser.sin_family=AF_INET;
ser.sin_port=htons(7879);
ser.sin_addr.s_addr=htonl(INADDR_ANY);
if((connect(sd,(struct sockaddr *)&ser,sizeof(ser)))==-1)
{
printf("Error on Connect");
return 0;
}
printf("Enter the source file name:");
scanf("%s",source);
printf("\nEnter the Destination file name:");
scanf("%s",dest);
send(sd,source,50,0);
fp=fopen(dest,"w");
29

recv(sd,rmsg,50,0);
while((strcmp(rmsg,"COMPLETED"))!=0)
{
fwrite(&rmsg,strlen(rmsg),1,fp);
bzero(&rmsg,50);
recv(sd,rmsg,50,0);
}
printf("File is received\n");
fclose(fp);
close(sd);
}
source.html
<HTML>
<HEAD>
<TITLE>
HTTP Program
</TITLE>
<BODY>
<font face= "Times New Roman">
<CENTER><H1> HOME PAGE</H1>
<MARQUEE BGCOLOR="PINK" DIRECTION="RIGHT"><FONT COLOR="green">
<B><I> COMPUTER NETWORK </I><B></MARQUEE></FONT>
</BODY>
</HTML>

Output:
Server:
[rit@cselinux ~]$ cc httpserver.c
[rit @cselinux ~]$ ./a.out
30

The File Name Is source.html


[rit @cselinux ~]$
Client:
[rit @cselinux httpclient]$ cc httpclient.c
[rit @cselinux httpclient]$ ./a.out
Enter the source file name:source.html
Enter the Destination file name:dest.html
File is received
[rit@cselinux httpclient]$
Dest.html:
<HTML>
<HEAD>
<TITLE>
HTTP Program
</TITLE>
<BODY>
<font face= "Times New Roman">
<CENTER><H1> HOME PAGE</H1>
<MARQUEE BGCOLOR="PINK" DIRECTION="RIGHT"><FONT COLOR="green">
<B><I> PSR ENGINEERING COLLEGE </I><B></MARQUEE></FONT>
</BODY>
</HTML>
Result:
Thus the program to implement HTTP was done and output was verified.

31

TO IMPLEMENT RPC (REMOTE PROCEDURE CALL)


Ex. No: 6
DATE:
Aim: To implement Remote Procedure call
RPC Server:
#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<stdlib.h>
#include<string.h>
#define PORT 6666
void main()
{
int sock1,sock2,i=PORT,l,x,y,z;;
char b[25],a[25],c[25];
struct sockaddr_in myaddr,client;
if((sock1=socket(AF_INET,SOCK_STREAM,0))==-1)
{
printf("\n\nSocket Creation Error.");
}
myaddr.sin_family=AF_INET;
myaddr.sin_port=htons(PORT);
myaddr.sin_addr.s_addr=htonl(INADDR_ANY);
if(bind(sock1,(struct sockaddr*)&myaddr,sizeof(struct sockaddr))!=-1)
{
printf("\n\nSocket is binded.");
}
else
{
printf("\nBinding error.");
}
if(listen(sock1,10)!=-1)
{
printf("\nListening Successful.");
}
else
{
printf("\nListening error..");
}
l=sizeof(client);
if((sock2=accept(sock1,(struct sockaddr*)&client,&l))!=-1)
{
printf("\nConnection accepted from client.");
}
else
{
32

printf("\nAccepting error.");
}
do
{
read(sock2,a,5);
if(strcmp("END",a)==0)
exit(0);
read(sock2,b,5);
read(sock2,c,5);
x=atoi(b);
y=atoi(c);
z=atoi(a);
switch(z)
{
case 1:z=x+y;
break;
case 2:z=x-y;
break;
case 3:z=x*y;
break;
case 4:z=x/y;
break;
}
sprintf(a,"%d",z);
write(sock2,a,5);
}while(1);
shutdown(sock2,2);
close(sock1);
}
Rpc Client:
#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<string.h>
#include<stdlib.h>
#define PORT 6666
void main()
{
int sock1,i=PORT,l;
char a[10],b[10];
struct sockaddr_in myaddr,client;
if((sock1=socket(AF_INET,SOCK_STREAM,0))==-1)
{
printf("\n\nSocket Creation Error.");
}
myaddr.sin_family=AF_INET;
myaddr.sin_port=htons(PORT);
33

myaddr.sin_addr.s_addr=htonl(INADDR_ANY);
l=connect(sock1,(struct sockaddr*)&myaddr,sizeof(myaddr));
if(l<0)
printf("\nError in connection.");
else
printf("\nConnected.");
do
{
printf("\nEnter the operation to be
performed:\n\t1.Addition\n\t2.Subtraction\n\t3.Multiplication\n\t4.Division\nEnter END to end.");
scanf("%s",a);
write(sock1,a,strlen(a));
if(strcmp(a,"END")==0)
exit(0);
printf("\nEnter the two operands:\n");
scanf("%s %s",a,b);
write(sock1,a,strlen(a));
write(sock1,b,strlen(b));
read(sock1,a,strlen(a));
printf("\nThe result is %s",a);
}while(1);
shutdown(sock1,2);
close(sock1);
}

RESULT:
Thus the RPC was implement successfully.

34

7 APPLICATIONS USING TCP SOCKETS


ECHO CLIENT AND ECHO SERVER
Ex. No: 7.1
DATE:
AIM: To write a program for implementing two way communication using TCP.
METHODOLOGY:
Transmission Control Protocol (TCP):
The Transmission Control Protocol is one of the core protocols of the Internet Protocol Suite.
TCP operates at a higher level, concerned only with the two end systems. TCP provides reliable,
ordered delivery of a stream of bytes from a program on one computer to another program on
another computer. TCP controls segment size, flow control, the rate at which data is exchanged, and
network traffic congestion.
TCP protocol operations may be divided into three phases. Connections must be properly
established in a multi-step handshake process (connection establishment) before entering the data
transfer phase. After data transmission is completed, the connection termination closes established
virtual circuits and releases all allocated resources.

Server:
Step 1: start a program.
Step 2: create a socket with address family AF_INET, type
protocol.

SOCK_STREAM and default

35

Step 3: Initialize the socket and assign any port number.


Step 4: Bind the server to the socket using bind() function.
Step 5: Establish the listen queue using the listen function.
Step 6: wait for client program on request, establish a connection using accept function.
Step 7: Repeat steps 8-10 until the server sends exit.
Step 8: Receive the message from the client using recv() and display the message.
Step 9: If the client message is exit go to step 11.
Step 10: Get the server message and send it to client using send() function.
Step 11: close the connection.
Step 12: Go to step 6.
Client:
Step 1: Start.
Step 2: Create a socket with address family AF_INET type SOCK_STERAM and default protocol.
Step 3: Initialize the socket and set it attributes set the required port number.
Step 4: Connect to the server using connect() function to initialize the request.
Step 5: Repeat steps 6-8 until server sends bye
Step 6: Accept the client message and send it to the server using send function.
Step 7: If the client message is exit go to step 9.
Step 8: Receive the message from the server using recv() and display the message.
Step 9: stop.

TCPSERVER:
36

#include<stdio.h>
#include<string.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<unistd.h>
#include<stdlib.h>
int main()
{
int sid,bd,lis,acptd,rd,sd;
struct sockaddr_in sin;
char buf[10];
socklen_t len;
sid=socket(PF_INET,SOCK_STREAM,0);
if(sid == -1)
{
printf("\n Error in creating socket \n");
exit(-1);
}
printf("\n The socket is created successfully");
memset(&sin,0,sizeof(sin));
sin.sin_family=AF_INET;
sin.sin_port=htons(5110);
sin.sin_addr.s_addr=htonl(INADDR_ANY);
bd=bind(sid,(struct sockaddr*)&sin,sizeof(sin));
if(bd < 0)
{
printf("\n Binding failed \n");
exit(-1);
}
printf("\n Binding Completed");
lis=listen(sid,5);
if(lis < 0)
{
printf("\n Error in listening \n");
exit(-1);
}
printf("\n Listening is completed");
len=sizeof(sin);
acptd=accept(sid,(struct sockaddr*)&sin,&len);
if(accept < 0)
{
37

printf("\n Error in Accepting \n");


exit(-1);
}
printf("\n Client is Accepted \n");
do
{
rd=read(acptd,buf,10);
if(rd < 0)
{
printf("\n Error in receiving the date from the client \n");
exit(-1);
}
printf(" Message received from client: %s \n",buf);
sd=send(acptd,buf,10,0);
if(sd < 0)
{
printf("\n Error in sending the data to the client \n");
exit(-1);
}
}while(strcasecmp(buf,"END")!=0);
shutdown(sid,2);
close(sid);
}
TCPClient :
#include<stdio.h>
#include<string.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<unistd.h>
#include<stdlib.h>
int main()
{
int sid,con,sd,rd;
struct sockaddr_in sin;
char buf[10];
sid=socket(PF_INET,SOCK_STREAM,0);
if(sid == -1)
{
printf("\n Error in creating the socket \n");
exit(-1);
}
printf("\n Socket created successfully");
38

memset(&sin,0,sizeof(sin));
sin.sin_family=AF_INET;
sin.sin_port=htons(5110);
sin.sin_addr.s_addr=htonl(INADDR_ANY);
con=connect(sid,(struct sockaddr*)&sin,sizeof(sin));
if(con < 0)
{
printf("\n The connection established falied \n");
exit(-1);
}
printf("\n Connection established successfully \n");
do
{
printf(" Enter the string: ");
scanf("%s",buf);
sd=send(sid,buf,10,0);
if(sd < 0)
{
printf("\n Error in sending the data to the server \n");
exit(-1);
}
rd=read(sid,buf,10);
if(rd < 0)
{
printf("\n Error in reading the data send by the server \n");
exit(-1);
}
printf(" The content received from sender is: %s \n",buf);
}while(strcasecmp(buf,"END")!=0);
shutdown(sid,2);
close(sid);
}
Output:
[test@ritlinux ~]$ cc tcpechoser.c
[test@ritlinux ~]$ ./a.out
The socket is created successfully
Binding Completed
Listening is completed
Client is Accepted
Message received from client: hai
Message received from client: hello
39

Message received from client: END


[test@ritlinux ~]$ cc tcpechocli.c
[test@ritlinux ~]$ ./a.out
Socket created successfully
Connection established successfully
Enter the string: hai
The content received from sender is: hai
Enter the string: hello
The content received from sender is: hello
Enter the string: END
The content received from sender is: END

40

Ex. No: 7.2


DATE:

CHAT
Aim: To Implement Half duplex and Full duplex using TCP
HALF DUPLEX CHAT USING TCP/IP
#include<sys/types.h>
#include<stdio.h>
#include<netdb.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<unistd.h>
#include<netinet/in.h>
int main(int argc,char *argv[])
{
int n,sd,ad;
struct sockaddr_in servaddr,cliaddr;
socklen_t clilen,servlen;
char buff[10000],buff1[10000];
bzero(&servaddr,sizeof(servaddr));
/*Socket address structure*/
servaddr.sin_family=AF_INET;
servaddr.sin_addr.s_addr=htonl(INADDR_ANY);
servaddr.sin_port=htons(5000);
/*TCP socket is created, an Internet socket address structure is filled with wildcard address &
servers well known port*/
sd=socket(AF_INET,SOCK_STREAM,0);
/*Bind function assigns a local protocol address to the socket*/
bind(sd,(struct sockaddr*)&servaddr,sizeof(servaddr));
/*Listen function specifies the maximum number of connections that kernel
should queue for this socket*/
listen(sd,5);
printf("%s\n","server is running");
/*The server to return the next completed connection from the front of the
completed connection Queue calls it*/
41

ad=accept(sd,(struct sockaddr*)&cliaddr,&clilen);
while(1)
{
bzero(&buff,sizeof(buff));
/*Receiving the request from client*/
recv(ad,buff,sizeof(buff),0);
printf("Receive from the client:%s\n",buff);
n=1;
while(n==1)
{
bzero(&buff1,sizeof(buff1));
printf("%s\n","Enter the input data:");
/*Read the message from client*/
fgets(buff1,10000,stdin);
/*Sends the message to client*/
send(ad,buff1,strlen(buff1)+1,0);
printf("%s\n","Data sent");
n=n+1;
}
}
return 0;
}
Client: hclient.c
#include<sys/types.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<unistd.h>
#include<stdio.h>
#include<netdb.h>
int main(int argc,char *argv[])
{
int n,sd,cd;
42

struct sockaddr_in servaddr,cliaddr;


socklen_t servlen,clilen;
char buff[10000],buff1[10000];
bzero(&servaddr,sizeof(servaddr));
/*Socket address structure*/
servaddr.sin_family=AF_INET;
servaddr.sin_addr.s_addr=inet_addr(argv[1]);
servaddr.sin_port=htons(5000);
/*Creating a socket, assigning IP address and port number for that socket*/
sd=socket(AF_INET,SOCK_STREAM,0);
/*Connect establishes connection with the server using server IP address*/
cd=connect(sd,(struct sockaddr*)&servaddr,sizeof(servaddr));
while(1)
{
bzero(&buff,sizeof(buff));
printf("%s\n","Enter the input data:");
/*This function is used to read from server*/
fgets(buff,10000,stdin);
/*Send the message to server*/
send(sd,buff,strlen(buff)+1,0);
printf("%s\n","Data sent");
n=1;
while(n==1)
{
bzero(&buff1,sizeof(buff1));
/*Receive the message from server*/
recv(sd,buff1,sizeof(buff1),0);
printf("Received from the server:%s\n",buff1);
n=n+1;
}
}
return 0;
}
43

SAMPLE OUTPUT:
Server:
(Host Name:Root1)
[root@localhost 4ita33]# vi hserver.c
[root@localhost 4ita33]# cc hserver.c
[root@localhost 4ita33]# ./a.out
Server is running
Receive from the client:hi
Enter the input data:
how are u da ..
Data sent
Receive from the client:me fine da ...
Enter the input data:
Client:
(Host Name:Root2)
[root@localhost 4ita33]# vi hclient.c
[root@localhost 4ita33]# cc hclient.c
[root@localhost 4ita33]# ./a.out 127.0.0.1
Enter the input data:
hi
Data sent:
Received from the server:how are u da ..
Enter the input data:
me fine da ...
Data sent

Result : Thus the chat application full duplex communication is established by sending the request
from the client to the server, server gets the message and gives response to the client and prints it.
FULL DUPLEX CHAT USING TCP/IP
#include<sys/types.h>
#include<sys/socket.h>
#include<stdio.h>
44

#include<unistd.h>
#include<netdb.h>
#include<arpa/inet.h>
#include<netinet/in.h>
int main(int argc,char *argv[])
{
int ad,sd;
struct sockaddr_in servaddr,cliaddr;
socklen_t servlen,clilen;
char buff[1000],buff1[1000];
pid_t cpid;
bzero(&servaddr,sizeof(servaddr));
/*Socket address structure*/
servaddr.sin_family=AF_INET;
servaddr.sin_addr.s_addr=htonl(INADDR_ANY);
servaddr.sin_port=htons(5500);
/*TCP socket is created, an Internet socket address structure is filled with wildcard address &
servers well known port*/
sd=socket(AF_INET,SOCK_STREAM,0);
/*Bind function assigns a local protocol address to the socket*/
bind(sd,(struct sockaddr*)&servaddr,sizeof(servaddr));
/*Listen function specifies the maximum number of connections that kernel should queue for
this socket*/
listen(sd,5);
printf("%s\n","Server is running.......");
/*The server to return the next completed connection from the front of the
completed connection Queue calls it*/
ad=accept(sd,(struct sockaddr*)&cliaddr,&clilen);
/*Fork system call is used to create a new process*/
cpid=fork();
if(cpid==0)
{
while(1)
{
bzero(&buff,sizeof(buff));
/*Receiving the request from client*/
recv(ad,buff,sizeof(buff),0);
printf("Received message from the client:%s\n",buff);
}
}
else
{
45

while(1)
{
bzero(&buff1,sizeof(buff1));
printf("%s\n","Enter the input data:");
/*Read the message from client*/
fgets(buff1,10000,stdin);
/*Sends the message to client*/
send(ad,buff1,strlen(buff1)+1,0);
printf("%s\n","Data sent");
}
}
return 0;
}
Client: fclient.c
#include<sys/socket.h>
#include<sys/types.h>
#include<stdio.h>
#include<arpa/inet.h>
#include<unistd.h>
#include<netdb.h>
#include<netinet/in.h>
int main(int argc,char *argv[])
{
int sd,cd;
struct sockaddr_in servaddr,cliaddr;
socklen_t servlen,clilen;
char buff[1000],buff1[1000];
pid_t cpid;
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family=AF_INET;
servaddr.sin_addr.s_addr=inet_addr(argv[1]);
servaddr.sin_port=htons(5500);
/*Creating a socket, assigning IP address and port number for that socket*/
sd=socket(AF_INET,SOCK_STREAM,0);
/*Connect establishes connection with the server using server IP address*/
cd=connect(sd,(struct sockaddr*)&servaddr,sizeof(servaddr));
/*Fork is used to create a new process*/
cpid=fork();
if(cpid==0)
{
while(1)
{
46

bzero(&buff,sizeof(buff));
printf("%s\n","Enter the input data:");
/*This function is used to read from server*/
fgets(buff,10000,stdin);
/*Send the message to
printf("%s\n","Data sent");
server*/
}
send(sd,buff,strlen(buff)+1,0);
}
el
while(1)
se
{
{
bzero(&buff1,sizeof(buff1));
/*Receive the message from server*/
}
recv(sd,buff1,sizeof(buff1),0);
return 0;
printf("Received message from the server:
}
%s\n",buff1);
SAMPLE OUTPUT:
}
Server:
(Host Name:Root1)
[root@localhost 4ita33]# vi fserver.c
[root@localhost 4ita33]# cc fserver.c
[root@localhost 4ita33]# ./a.out
Server is running.......
Enter the input data:
Received message from the client:hi
how are u
Data sent
Enter the input data:
Receiv Client:
(Host Name:Root2)
[root@localhost 4ita33]# vi fclient.c
[root@localhost 4ita33]# cc fclient.c
[root@localhost 4ita33]# ./a.out 127.0.0.1
Enter the input data:
hi
Data sent
Enter the input data:
Received message from the server:how are u
i am fine
Data sent
Enter the input data:
Result:
47

Thus the chat application full duplex communication is established by sending the
request from the client to the server, server gets the message and gives response to the
client and prints it. ed message from the client:i am fine

48

FILE TRANSFER
Ex. No: 8.3
DATE:
Aim: To implement File transfer
Server: ftps.c
#include<sys/types.h>
#include<sys/socket.h>
#include<sys/stat.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<netdb.h>
#include<unistd.h>
#include<stdio.h>
include<string.h>
int main(int argc,char *argv[])
{
int sd,ad,size;
struct sockaddr_in servaddr,cliaddr;
socklen_t clilen;
clilen=sizeof(cliaddr);
struct stat x;
char buff[100],file[10000];
FILE *fp;
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family=AF_INET;
servaddr.sin_addr.s_addr=htonl(INADDR_ANY);
servaddr.sin_port=htons(1500);
sd=socket(AF_INET,SOCK_STREAM,0);
bind(sd,(struct sockaddr*)&servaddr,sizeof(servaddr));
listen(sd,5);
printf("%s\n","Server Is Running....");
ad=accept(sd,(struct sockaddr*)&cliaddr,&clilen);
while(1)
{
bzero(buff,sizeof(buff));
bzero(file,sizeof(file));
recv(ad,buff,sizeof(buff),0);
fp=fopen(buff,"r");
stat(buff,&x);
size=x.st_size;
fread(file,sizeof(file),1,fp);
send(ad,file,sizeof(file),0);
49

}
}
Client: ftpc.c
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<netdb.h>
#include<stdio.h>
#include<unistd.h>
int main(int argc,char *argv[])
{
int sd,cd;
struct sockaddr_in servaddr,cliaddr;
socklen_t clilen;
char buff[100],file[10000];
struct hostent *h;
h=gethostbyname(argv[1]);
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family=h->h_addrtype;
memcpy((char *)&servaddr.sin_addr.s_addr,h->h_addr_list[0],h->h_length);
servaddr.sin_port=htons(1500);
sd=socket(AF_INET,SOCK_STREAM,0);
cd=connect(sd,(struct sockaddr*)&servaddr,sizeof(servaddr));
while(1)
{
printf("%s\n","Enter the File Name :");
scanf("%s",buff);
send(sd,buff,strlen(buff)+1,0);
printf("%s\n","File Output :");
recv(sd,file,sizeof(file),0);
printf("%s",file);
}
return 0;
}
SAMPLE OUTPUT:
Server:
(Host Name:Root1)
[root@localhost 4ita33]# vi ftps.c
[root@localhost 4ita33]# cc ftps.c
[root@localhost 4ita33]# ./a.out
Server is Running
FILE REACHED
File output : this is my network lab
50

Client:
(Host Name:Root2)
[root@localhost 4ita33]# vi ftpc.c
[root@localhost 4ita33]# cc ftpc.c
[root@localhost 4ita33]# ./a.out
Enter the filename:
ita.txt

Sending the file content


Data sent.....

Result: Thus the FTP client-server communication is established and data is transferred between the
client and server machines.

51

9. APPLICATIONS USING TCP AND UDP SOCKETS


Ex. No: 9.1
DATE:
AIM:

To write a c program to implement DNS application.

METHODOLOGY:
Definition
The Domain Name System (DNS) is basically a large database which resides on various
computers and it contains the names and IP addresses of various hosts on the internet and various
domains. The Domain Name System is similar to a file system in UNIX or DOS starting with a root.
Branches attach to the root to create a huge set of paths. Each branch in the DNS is called a label. The
domain name system database is divided into sections called zones. The name servers in their
respective zones are responsible for answering queries for their zones. A zone is a subtree of DNS and
is administered separately. There are multiple name servers for a zone. There is usually one primary
name server and one or more secondary name servers. A name server may be authoritative for more
than one zone.
DNS names are assigned through the Internet Registries by the Internet Assigned Number
Authority (IANA). The domain name is a name assigned to a domain. For example, mycollege.edu
represents the domain name of an educational institution.Three main components of DNS

Resolver

Name server

Database of resource records(RRs)

In UNIX the resolver is accessed by using the library functions "gethostbyname" and
"gethostbyaddr". The resolver will send requests to the name servers to return information requested
by the user. The requesting computer tries to connect to the name server using its IP address rather than
the name.

52

Structure and message format:


The drawing below shows a partial DNS hierarchy. At the top is what is called the root and it is
the start of all other branches in the DNS tree. It is designated with a period. Each branch moves down
from level to level. When referring to DNS addresses, they are referred to from the bottom up with the
root designator (period) at the far right. Example: "myhost.mycompany.com.

Algorithm:
Server:
1. Start the program.
2. Create the socket, establish a connection using accept function.
3. Get the domain name from the client.
4. Match the domain name to the corresponding IP address and send it to client.
5. Close the connection.
6. Stop the program.
Client:
1. Start the program.
2. Create the socket and Connect to the server using connect() function.
3. Send the domain name to the DNS server.
4. Receive the corresponding IP address from the server.
5. Display the address.
6. Close the socket.
53

DNS Server1:
#include<stdio.h>
#include<string.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<unistd.h>
#include<time.h>
int main()
{
int sid,i,j,len,k=0,sid1;
char buf1[200],buf2[20],buf3[20],buf[200],msg[200];
struct sockaddr_in sin,sin1;
sid=socket(PF_INET,SOCK_DGRAM,0);
memset(&sin,0,sizeof(sin));
sin.sin_family=AF_INET;
sin.sin_port=htons(5111);
sin.sin_addr.s_addr=htonl(INADDR_ANY);
len=sizeof(sin);
bind(sid,(struct sockaddr *)&sin,len);
recvfrom(sid,&msg,sizeof(msg),0,(struct sockaddr *)&sin,&len);
if(!strcasecmp(msg,"Gmail"))
{
strcpy(buf,"124.124.252.113");
strcpy(buf1,"Server1");
}
else if(!strcasecmp(msg,"Yahoomail"))
{
strcpy(buf,"25.255.169.86");
strcpy(buf1,"server1");
}
else if(!strcasecmp(msg,"Rediffmail"))
{
strcpy(buf,"225.176.16.254");
54

strcpy(buf1,"server1");
}
else
{
strcpy(buf1,"server2");
sid1=socket(PF_INET,SOCK_DGRAM,0);
memset(&sin1,0,sizeof(sin1));
sin1.sin_family=AF_INET;
sin1.sin_port=htons(4111);
sin1.sin_addr.s_addr=htonl(INADDR_ANY);
len=sizeof(sin1);
sendto(sid1,&msg,sizeof(msg),0,(struct sockaddr *)&sin1,len);
recvfrom(sid1,&buf,sizeof(buf),0,(struct sockaddr *)&sin1,&len);
}
sendto(sid,&buf,sizeof(buf),0,(struct sockaddr *)&sin,len);
sendto(sid,&buf1,sizeof(buf),0,(struct sockaddr *)&sin,len);
printf("\n Disconnected \n");
close(sid);
shutdown(sid,0);
}
DNS Server2.c
#include<stdio.h>
#include<string.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<unistd.h>
#include<time.h>
int main()
{
int sid,i,j,len,k=0;
char buf1[20],buf2[20],buf3[20],buf[200],msg[200];
struct sockaddr_in sin;
sid=socket(PF_INET,SOCK_DGRAM,0);
55

memset(&sin,0,sizeof(sin));
sin.sin_family=AF_INET;
sin.sin_port=htons(4111);
sin.sin_addr.s_addr=htonl(INADDR_ANY);
len=sizeof(sin);
bind(sid,(struct sockaddr *)&sin,len);
recvfrom(sid,&msg,sizeof(msg),0,(struct sockaddr *)&sin,&len);
if(!strcasecmp(msg,"Wikipedia"))
{
strcpy(buf,"208.80.152.2");
sendto(sid,&buf,sizeof(buf),0,(struct sockaddr *)&sin,len);
}
else if(!strcasecmp(msg,"Google"))
{
strcpy(buf,"126.83.15.245");
sendto(sid,&buf,sizeof(buf),0,(struct sockaddr *)&sin,len);
}
else if(!strcasecmp(msg,"Bing"))
{
strcpy(buf,"88.280.125.20");
sendto(sid,&buf,sizeof(buf),0,(struct sockaddr *)&sin,len);
}
else
{
strcpy(buf,"Notfound");
sendto(sid,&buf,sizeof(buf),0,(struct sockaddr *)&sin,len);
}
printf("\n Disconnected \n");
close(sid);
shutdown(sid,0);
}
DNSClient
#include<stdio.h>
#include<string.h>
#include<sys/types.h>
56

#include<sys/socket.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<unistd.h>
int main()
{
int sid,i,j,len,k=0,sid1;
char buf[200],msg[200],buf1[200];
struct sockaddr_in sin,sin1;
sid=socket(PF_INET,SOCK_DGRAM,0);
memset(&sin,0,sizeof(sin));
sin.sin_family=AF_INET;
sin.sin_port=htons(5111);
sin.sin_addr.s_addr=htonl(INADDR_ANY);
len=sizeof(sin);
printf("\nEnter website name:");
scanf("%s",msg);
sendto(sid,&msg,sizeof(msg),0,(struct sockaddr *)&sin,len);
recvfrom(sid,&buf,sizeof(buf),0,(struct sockaddr *)&sin,&len);
recvfrom(sid,&buf1,sizeof(buf),0,(struct sockaddr *)&sin,&len);
printf("IP:%s\t From->%s\n",buf,buf1);
close(sid);
shutdown(sid,0);
}
Output
[test@ritlinux ~]$ cc dnsser1.c
[test@ritlinux ~]$ ./a.out
Disconnected
[test@ritlinux ~]$ cc dnsser2.c
[test@ritlinux ~]$ ./a.out
Disconnected
[test@ritlinux ~]$ cc dnscli.c
[test@ritlinux ~]$ ./a.out
Enter website name:Google
IP:126.83.15.245

From->server2
57

[test@ritlinux ~]$ cc dnscli.c


[test@ritlinux ~]$ ./a.out
Enter website name:hotmail
IP:Notfound

From->server2

Result:
Thus the program to implement DNS was done and output was verified

10. STUDY OF NETWORK SIMULATOR (NS).


Ex. No: 10.
DATE:
10. NS 2 Overview
NS (Network Simulartor) is an event driven network simulator developed at UC Berkeley that
simulates variety of IP networks. It implements network protocols such as TCP and UPD, traffic
source behavior such as FTP, Telnet, Web, CBR and VBR, router queue management mechanism such
as Drop Tail, RED and CBQ, routing algorithms such as Dijkstra, and more. NS also implements
multicasting and some of the MAC layer protocols for LAN simulations.
The NS project is now a part of the VINT project that develops tools for simulation results display,
analysis and converters that convert network topologies generated by well-known generators to NS
formats. Currently, NS (version 2) written in C++ and OTcl (Tcl script language with Object-oriented
extensions developed at MIT) is available.

Figure 1. Simplified User's View of NS


As shown in Figure 1, in a simplified user's view, NS is Object-oriented Tcl (OTcl) script interpreter
that has a simulation event scheduler and network component object libraries, and network setup
(plumbing) module libraries (actually, plumbing modules are implemented as member functions of the
base simulator object). In other words, to use NS, you program in OTcl script language..
NS is written not only in OTcl but in C++ also. For efficiency reason, NS separates the data path
implementation from control path implementations. In order to reduce packet and event processing
time (not simulation time), the event scheduler and the basic network component objects in the data
58

path are written and compiled using C++. These compiled objects are made available to the OTcl
interpreter through an OTcl linkage that creates a matching OTcl object for each of the C++ objects
and makes the control functions and the configurable variables specified by the C++ object act as
member functions and member variables of the corresponding OTcl object. In this way, the controls of
the C++ objects are given to OTcl. It is also possible to add member functions and variables to a C++
linked OTcl object. The objects in C++ that do not need to be controlled in a simulation or internally
used by another object do not need to be linked to OTcl. Likewise, an object (not in the data path) can
be entirely implemented in OTcl. Figure 2 shows an object hierarchy example in C++ and OTcl. One
thing to note in the figure is that for C++ objects that have an OTcl linkage forming a hierarchy, there
is a matching OTcl object hierarchy very similar to that of C++.

Figure 2. C++ and OTcl: The Duality


Figure 3 shows the general architecture of NS. In this figure a general user (not an NS developer) can
be thought of standing at the left bottom corner, designing and running simulations in Tcl using the
simulator objects in the OTcl library. The event schedulers and most of the network components are
implemented in C++ and available to OTcl through an OTcl linkage that is implemented using tclcl.
The whole thing together makes NS, which is a OO extended Tcl interpreter with network simulator
libraries.

Figure 3. Architectural View of NS


When a simulation is finished, NS produces one or more text-based output files that contain detailed
simulation data, if specified to do so in the input Tcl (or more specifically, OTcl) script. The data can
be used for simulation analysis or as an input to a graphical simulation display tool called Network
Animator (NAM) that is developed as a part of VINT project. NAM has a nice graphical user interface
similar to that of a CD player (play, fast forward, rewind, pause and so on), and also has a display
speed controller. Furthermore, it can graphically present information such as throughput and number of
packet drops at each link, although the graphical information cannot be used for accurate simulation
analysis.
OTcl ( Object Oriented Tcl)
Knowing that OTcl is Object-orieneted extension of Tcl, it is obvious that all Tcl commands work on
OTcl - the relationship between Tcl and Otcl is just same as C and C++.
File name :
File name must have the extension .tcl
Syntax :
59

1. Assigning a value to a variable :


Eg : a = 10 is written as
set a 10
Eg 2 :
set X This is a string
Eg 3 :
set y 1.57
2. Getting the variable value :
Eg : getting the value of variable a
$a
3. Expression :
a+b is written as
[expr $a + $b]
4. Assigning the value of an expression :
c = a+b is wriiten as
set c [expr $a + $b]
5. If. Else statement :
if { $k <10}
{
puts k< 10
}
else {
puts K >= 10
}
6. Switch Statement :
Syntax :
switch string { pattern1 body1 ?pattern2 body2?...?patternN
bodyN? }
Eg :
switch $x {
$z {
Set y1 [expr {$y+1}]
}
ONE {
Set y1 [expr {$y+1}]
TWO {
Set y1 [expr {$y + 2}]
default {
puts $x is not a match
}
}
7. Printing :
Eg :
set name Hello World
puts $name
It prints Hello World
Note : Each time puts command is called, a new line is started. To avoid new
line , add -nonewline after puts.
60

Eg :
puts Sample :
puts -nonewline $name
will print
Sample : Hello World
8. Printing into file :
Eg : writing the value of number into the file filename
puts $fileName $number
9. Tabulating in a file :
It is done with \t
Eg :
puts $fileName $number \t $no2
10. For Loop :
for( i= 0; i<5; i++)
{
------------------}
can be written as
for { set i 0} {$i < 5} {incr i}
{
---------------}
}
11. While loop :
Syntax :
while condition body
Eg :
while {$x <= 5}
{
puts x = $x
set y [expr {$x+2}]
}
12. Procedure/ Function :
Syntax :
proc name {args} { body}
Eg :
proc sum {arg1 arg2 } {
set x [expr {$arg1 + $arg2}]
return $x
}
13. Calling the procedure :
Calling the above procedure is
sum 2 5
14. global command:
61

global command will causes a variable in a local scope (inside a procedure) to refer to the
global variable of that name.
Eg :
set a 10
-------------------proc sum {b}
{
global a
set x [expr {$a + $b}}
return $x
}
15. Running the program
The command for running the tcl program is
ns filename.tcl
---------------Simulating a Simple Network
1. Creating a Simulator Object :
Eg :
set ns [new Simulator]
variable name

What this line does is the following:


* Initialize the packet format
* Create a scheduler
* Select the default address format
The "Simulator" object has member functions that do the following:

o
o

Create compound objects such as nodes and links


Connect network component objects created (ex. attach-agent)

Set network component parameters (mostly for compound objects)

Create connections between agents (ex. make connection between a "tcp" and "sink")

Specify NAM display options

Etc.

62

The "Simulator" object member function implementations are located in the "ns-2/tcl/lib/ns-lib.tcl"
file.
2 Creating a node :
Eg :
set n0 [$ns node]
variable name for node number

simulator object

3. Coloring a node :
Eg :
$n0 color red
4. Shape for a node :
Eg:
$n1 shape box
or
hexagon
or
circle (default)
5. Creating link between nodes :
Eg 1:
n
0

$ns duplex- link


Simulator object

n
2

$n0

$n2

2Mb

link type

10ms

node numbers speed

DropTail
max.delay

Packet dropping mechanism

Eg2 :

n
1

n
2

$ns simplex-link $n1 $n2 5Mb 20 ms DropTail


Eg 3 :
$ns simplex-link $n1 $n2 5Mb 20 ms RED
6. Setting Queue size of a link :
Eg : setting the queue size of link between node n2 and n3 to 10
$ns queue-limit $n2 $n3 10
7. Monitoring the queue (for NAM) :
63

Eg :
Monitoring the queue between n2 and n3 at every 0.5 sec is
$ns duplex-link-op $n2 $n3 queuePos 0.5
8. Setting up a TCP connection :
Eg :
Adding TCP agent to node n0
ft
p
TCP
n
0

n
2

n
3

TCP Sink

n
1

Establishing TCP Source :


set tcp [new Agent/TCP]
variable name
$ns attach-agent $n0 $tcp
Establishing TCP Sink :
set sink [new Agent/TCPSink]
Variable name
$ns attach-agent $n3 $sink
Connecting Source and Sink:

$ns connect $tcp $sink

9. Setting up FTP traffic over TCP Connection:


set ftp [new Application/FTP]
variable name
$ftp attach-agent $tcp
10. Setting up a UDP connection :
Eg :
Adding UDP agent to node n1

n
0

n
2

n
3

64

NULL
n
1

UDP

cb
r

Establishing UDP Source :


set udp [new Agent/UDP]
variable name
$ns attach-agent $n1 $udp
Establishing NULL Sink :
set null [new Agent/Null]
variable name
$ns attach-agent $n3 $null
Connecting Source and Sink:
$ns connect $udp $null
11. Setting up CBR Traffic over UDP Connection:
set cbr [new Application/Traffic/CBR]
variable name
$cbr attach-agent $udp
12. Setting up values for Traffic :
Eg : Setting values for CBR Traffic :
Setting traffic type :
$cbr set type_ CBR
Setting Packet Size :
$cbr set packet_size_ 2000
Setting Traffic Rate :
65

$cbr set rate_ 1 mb


13. Printing CBR packet size and interval:
Eg :
puts CBR packet size = [$cbr set packet_size_]
puts CBR interval = [$cbr set interval_]
14. Setting id for Flow :
Eg : Setting Flow id for TCP Connection :
$tcp set fid_ 1
Eg2 : Setting Flow id for UDP Connection :
$udp set fid_ 2
15. Setting colors for flow : (for NAM)
Eg :
$ns color 1 Blue
Flow id
Eg2: $ns color 2 Red
16. Scheduling events for Traffic :
Eg :
$ns at 0.1 $cbr start
Time

traffic

Eg2 :
$ns at 1.0 $ftp start
Eg 3 :
$ns at 4.0 $cbr stop
17. Queue Monitoring :
Eg : Monitoring the queue between n2 and n3 every 0.1 sec and storing the result in the file
qm.out
set qmon

[$ns monitor-queue] $n2 $n3 [open qm.out w] 0.1]

variable name

node numbers

output file name

write mode

time interval

[$ns link $n2 $n3 ] queue-sample-timeout


The output trace file contains the following 11 columns :

time
input node
output node
queue size in bytes (size_)
queue size in packets (pkt_)
no. of packets arrived (parrivals_)
66

no. of packets departured (pdepartures_)


no. of packets dropped (pdrops_)
no. of bytes arrived (barrivals_)
no. of bytes departured (bdepartures_)
no. of bytes dropped (bdrops_)

18. Accessing values in Trace files for Queue Monitoring :


$qmon instvar parrivlas_

pdepartures_

pdrops_

set packetLost [expr $parrivals_ -$pdepartures_ - $pdrops_]


set time 0.05
set now [$ns now]
set t [$now + $time]
set bandwidth [expr $bdepartures_*8/1024/$t]
19. Tracing Simulation results :
Trace file can be created for storing simulation results.
Eg :
set file1 [open out.tr w]
file pointer

file name

write mode

$ns trace-all file1


20. Creating Trace file for NAM Visualization:
Eg :
set file2 [open out.nam w}
$ns namtrace-all file2
21. Procedure for plotting Window size :
Eg :
proc plotWindow { tcpSource file}
{
global ns
set time 0.01
# current time
set now [$ns now]
#current window size from tcp tcpSource
set cwnd [$tcpSoucre set cwnd_]
#write current time & current window size into file file
puts $file $now $cwnd
#call the procedure at an interval of time sec
$ns at [expr $now + $time] plotWindow $tcpSource $file
}
Starting the procedure plotWindow at 0.1 sec :
$ns at 0.1 plotWindow $tcp $Winfile
67

21. Giving Node position for NAM :


Eg :
n
0
n
2

$ns duplex-link-op $n0 $n2 orient right-down


22. Adding label to Link :
Eg : Adding Label TCP Link for link from node n0 to node 2
$ns duplex-link-op $n0 $n2 label TCP Link
23. Adding Text at the bottom of NAM Window :
Eg :
$ns at 5 $ns trace-annotate \Packet drop\
24. Finishing procedure :
All trace file contents must be used . NAM trace file must be closed . NAM trace file can be
executed in background .
Eg :
proc finish { } {
global ns file1 file2
$ns flush-trace
close $file2
exec nam out.nam &
# Run in background
exit 0
}
25. Plotting graph with xgraph :
xgraph uses one or more ascii files containing x-y data point per line.
Options :
Title : -t Title
Size : -geometry xsize x ysize
Title for X-axis : -x xaxisTitle
Title for Y-axis : -y yaxisTitle
Eg :
exec xgraph out.tr out.nam -geometry 800x400 t Lost Rates -x
Time -y Lost Packets &
run in background
26. Running the Simulation :
$ns run
Program Outline
#Create a simulator object
set ns [new Simulator]
68

#Open the trace file(s)


set nf [open out.nam w]
$ns namtrace-all $nf
#Define a 'finish' procedure
proc finish {} {
global ns nf
$ns flush-trace
close $nf; #Close the trace file
exec nam out.nam & #Execute nam on the trace file
#(optional)
exit 0
}
Place your code here
#Call the finish procedure after 5 seconds simulation time
$ns at 5.0 "finish"
#Run the simulation
$ns run
Lab Exercise :
1. Simulate the following network :
sources
n
1

16Mb, 25 ms
16 Mb, 25 ms

n
2

54Mb, 12ms
1

n
3

n
5

100Mb, 8ms

n
6

6Mb, 25ms

n
7

destination

25Mb, 50ms
n
4

n1 n7 - FTP traffic
n4 n7 - CBR traffic
Implement DropTail & RED scheme in the overloaded link and plot both window size and packets
dropped.
2. Simulate the following network :

n
5

75 Mb, 25ms

N
1
n
2

69

75Mb, 25ms
n
4

n
3

25Mb, 20ms

100Mb, 20ms
n1 n5 FTP traffic n2 -- n4 CBR Traffic
Implement DropTail & RED scheme in the overloaded link and plot both window size and packets
dropped.

70

11 PERFORM A CASE STUDY ABOUT THE DIFFERENT ROUTING ALGORITHMS TO


SELECT THE NETWORK PATH WITH ITS OPTIMUM AND ECONOMICAL DURING
DATA TRANSFER
Ex. No: 11.
DATE:
// Link State Routing
Program Coding:
#include<stdio.h>
#include<conio.h>
struct packet
{
intadj[15];
int cost[15];
intcnt;
}PACKET[15];
int rout;
intdist[15][15];
int via;
input()
{
char ch='y';
intx,y,l=6,m=9,co;
inti,j;
printf(" No of Routers:");
scanf("%d",&rout);
for(i=1;i<=rout;i++)
{
for(j=1;j<=rout;j++)
{
dist[i][j]=9999;
}
}
gotoxy(6,7);
printf("From to cost ( y/n)");
while(ch=='y')
{
co=0;
gotoxy(l,m);
scanf("%d",&x);
gotoxy(l+6,m);
scanf("%d",&y);
gotoxy(1+15,m);
scanf("%d",&co);
dist[x][y]=co;
71

dist[y][x]=co;
gotoxy(1+24,m);
fflush(stdin);
scanf("%c",&ch);
m++;
}
}
pckt()
{
inti,j;
int count;
for(i=1;i<=rout;i++)
{
count=1;
for(j=1;j<+rout;j++)
{
if(dist[i][j]!=9999)
{
PACKET[i].adj[count]=j;
PACKET[i].cost[count]=dist[i][j];
count++;
}
PACKET[i].cnt=count-1;
}
}
}
build()
{
inti,j,k;
intflg=0;
getch();
clrscr();
printf("Buffer Router Table For %d\n",via);
printf("---------------------------------\n");
printf(" SRC SENT/ACK\n");
printf("-----------------\n");
for(i=1;i<=rout;i++)
{
printf("%d>>",i);
for(j=1;j<=PACKET[via].cnt;j++)
{
flg=1;
for(k=1;k<=PACKET[i].cnt;k++)
{
if(via==i)
goto outer;
72

if(PACKET[via].adj[j]==i)
flg=0;
if(PACKET[via].adj[j]==PACKET[i].adj[k])
flg=0;
}
if(j<=PACKET[via].cnt);
{
if(flg==1)
printf("%dSNT ",PACKET[via].adj[j]);
if(flg==0)
printf("%dACK ",PACKET[via].adj[j]);
}
}
outer:;
printf("\n");
}}
int main()
{
clrscr();
printf("\t\t\t Link State Routing\n");
printf("Stage 1: Router Input\n");
input();
printf("Stage 2: PACKET Construction\n");
pckt();
printf("Stage 3: VIA Router\n");
printf("Router:");
scanf("%D",&via);
printf("\n Stage 4: Building Buffer Table\n");
build();
}

// Flooding
Program Coding:
#include<stdio.h>
#include<conio.h>
#include<dos.h>
int g[20][20],v,e;
void main()
{
int i,j,v1[10],source,a,b,dest;
char msg[50];
clrscr();
//Number of Routers
printf("Enter the no.of.hosts");
73

scanf("%d",&v);
//Number of Connections in Network
printf("Enter the no.of.links:");
scanf("%d",&e);
for(i=0;i<=v;i++)
for(j=1;j<=e;j++)
{
g[i][j]=0;
g[j][i]=0;
}
for(i=1;i<=v;i++)
v1[i]=1;
printf("Enter the link between a and b:");
for(i=1;i<=e;i++)
{
scanf("%d%d",&a,&b);
g[a][b]=1;
}
//First sending router
printf("Enter the host who want to send the package to other hosts:");
scanf("%d",&source);
//Destination Router
printf("Enter the actual destination hosts:");
scanf("%d",&dest);
//Message to be sent
printf("Enter the msg to be sent:");
scanf("%s",&msg);
//Check if Destination Router sends back message to the source
if(g[dest][source]==g[source][dest])
{
g[dest][source]=0;
printf("\nPacket cannot be transmitted from %d to host %d",dest,source);
}
//Message transmitted to all Routers
for(i=1;i<=v;i++)
for(j=1;j<=v;j++)
{
if((g[i][j]!=0)&&(source!=j)&&(v1[j]!=0)
{
printf("\n\nPlease wait...Packages are being transmitted...");
delay(1000);
printf("\nPackages are passed from hosts %d to host %d",i,j);
printf("\n message received by host%d is:%s",j,msg);
if(g[i][j]=g[j][i])
{
printf("\n\nPackage cannot be transmitted from host %d to host %d",j,i);
74

}
}
}getch();
}
// Distance vector
Program Coding:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct table
{
int des;
int hc;
char nh[3];
}table;
typedef struct ripmsg
{
int des;
int hc;
}ripmsg;
int main()
{
table t[10],t1[10];
ripmsg r[10];
char ch[3];
int k,j=0,n,n1,i;
int flag;
int flag1;
printf("Enter No Of Entries In Old RT:");
scanf("%d",&n);
printf("Enter Des,Hc,Nh:");
for(i=0;i<n;i++)
{
scanf("%d %d %s",&t[i].des,&t[i].hc,&t[i].nh);
}
printf("Enter Rip Msg From Where ? :");
scanf("%s",&ch);
printf("Enter No Of Entries In Rip Msg:");
scanf("%d",&n1);
printf("Enter Des,Hc:");
for(i=0;i<n1;i++)
{
scanf("%d %d",&r[i].des,&r[i].hc);
}
75

k=n;
for(i=0;i<n;i++)
{
t1[i]=t[i];
}
for(i=0;i<n1;i++)
{
flag=0;
for(j=0;j<n;j++)
{
if(t1[j].des==r[i].des)
{
flag1=0;
if(strcmp(t1[j].nh,ch)==0)
{
t1[j].des=r[i].des;
t1[j].hc=r[i].hc+1;
flag1=1;
}
if(flag1==0)
if(t1[j].hc>r[i].hc+1)
{
t1[j].des=r[i].des;
t1[j].hc=r[i].hc+1;
strcpy(t1[j].nh,ch);
}
flag=1;
}
}
if(flag==0)
{
t1[k].des=r[i].des;
t1[k].hc=r[i].hc+1;
strcpy(t1[k].nh,ch);
k++;
}
}
printf("\n\nOld Routing Table");
printf("\nDestination HopCount NextHop");
for(i=0;i<n;i++)
{
printf("\n\t%d \t%d \t%s",t[i].des,t[i].hc,t[i].nh);
}
printf("\n\nRip Msg From %s ",ch);
printf("\nDestination HopCount");
for(i=0;i<n1;i++)
{
printf("\n\t%d \t%d",r[i].des,r[i].hc);
}
printf("\n\nNew Routing Table");
76

printf("\nDestination HopCount NextHop");


for(i=0;i<k;i++)
{
printf("\n\t%d \t%d \t%s",t1[i].des,t1[i].hc,t1[i].nh);
}
}

77

Das könnte Ihnen auch gefallen