Beruflich Dokumente
Kultur Dokumente
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.
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.
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.
#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
}
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
Result:
Thus the program to simulate sliding window protocol was done and output was verified.
10
#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.
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
SOCK_DGRAM
reliable, in-order
SOCK_STREAM
raw socket
SOCK_RAW
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
where:
13
o
o
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:
where:
o
o
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
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:
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
recv(),
readfrom(),
15
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)
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
*toaddrptr is address of sockaddr_in structure holding destination address info. Must be cast
to type sockaddr.
OK return code does NOT imply data correctly delivered, only correctly sent
int recvfrom (int sockfd, char *buff, int bufflen, int flags, struct sockaddr *fromaddrptr,
int *addresslen)
Function
name
action
htonl
ntohl
format
htons
ntos
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
RESULT:
Thus the ARP and RARP was implement successfully.
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
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.
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
31
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
Server:
Step 1: start a program.
Step 2: create a socket with address family AF_INET, type
protocol.
35
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
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
40
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
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
Result: Thus the FTP client-server communication is established and data is transferred between the
client and server machines.
51
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
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
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
From->server2
Result:
Thus the program to implement DNS was done and output was verified
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++.
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
o
o
Create connections between agents (ex. make connection between a "tcp" and "sink")
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
n
2
$n0
$n2
2Mb
link type
10ms
DropTail
max.delay
Eg2 :
n
1
n
2
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
n
0
n
2
n
3
64
NULL
n
1
UDP
cb
r
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
variable name
node numbers
write mode
time interval
time
input node
output node
queue size in bytes (size_)
queue size in packets (pkt_)
no. of packets arrived (parrivals_)
66
pdepartures_
pdrops_
file name
write mode
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
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
77