0% found this document useful (0 votes)
101 views

NETWORK - LAB Old PDF

This document provides an overview of the ISO/OSI network model and Unix socket programming. It describes the seven layers of the ISO/OSI model from the physical layer to the application layer and their functions. It also discusses the differences between the ISO/OSI model and the TCP/IP model. For Unix socket programming, it defines sockets, socket communication domains, socket types, and address formats used for communication between applications on different machines.

Uploaded by

Bubblee Bennu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
101 views

NETWORK - LAB Old PDF

This document provides an overview of the ISO/OSI network model and Unix socket programming. It describes the seven layers of the ISO/OSI model from the physical layer to the application layer and their functions. It also discusses the differences between the ISO/OSI model and the TCP/IP model. For Unix socket programming, it defines sockets, socket communication domains, socket types, and address formats used for communication between applications on different machines.

Uploaded by

Bubblee Bennu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 72

V.R.S.

COLLEGE OF ENGINEERING AND TECHNOLOGY

ARASUR

CS1305 – NETWORK LABORATORY MANUAL

(SEMESTER - V)

DEPARTMENT OF COMPUTER SCIENCE AND


ENGINEERING
TABLE OF CONTENTS

PAGE
S.No. TITLE
No.
1. Study of ISO/OSI Network Model 3

2. Unix Socket Programming 8

3. Bit Stuffing and CRC Computation 12

4. Simulation of ARP / RARP 17

5. Simulation of Sliding Window Protocol 26

6. Chat Application 33

7. Simulation of OSPF Routing Protocol 40

8. Domain Name System 46

9. Downloading a File 50

10. Data Transfer over RS232 55

11. Study of NS2 (Network Simulator version 2) Simulator 58

12. Study of OPNET ( OPtimized NETwork ) Simulator 62

Appendix 67

-2-
1. STUDY OF ISO/OSI NETWORK MODEL

INTRODUCTION:

The ISO (International Standards Organization) has created a layered model


called the OSI (Open Systems Interconnect) model to describe defined layers in a
network operating system. The purpose of the layers is to provide clearly defined
functions to improve internetwork connectivity between "computer" manufacturing
companies. Each layer has a standard defined input and a standard defined output. Let
us study about the various layers of ISO/OSI Model.

SEVEN LAYERS OF ISO/OSI MODEL:

The seven layers of ISO/OSI model are given below:

1. Physical Layer (Bottom layer)


2. Data Link Layer
3. Network Layer
4. Transport Layer
5. Session Layer
6. Presentation Layer
7. Application Layer (Top Layer)

PHYSICAL LAYER:
The Physical layer concerns itself with the transmission of bits and the
network card's hardware interface to the network. The hardware interface involves the
type of cabling (coax, twisted pair, etc..), frequency of operation (1 Mbps, 10Mbps,
etc..), voltage levels, cable terminations, topography (star, bus, ring, etc..), etc..
Examples of Physical layer protocols are 10Base5 - Thicknet, 10Base2 - Thinnet,
10BaseT - twisted pair, ArcNet, FDDI, etc...

-3-
DATA LINK LAYER:
The Data Link layer is a firmware layer of the network interface card. The
Data Link layer puts the datagram into packets (frames of bits: 1s & 0s) for
transmission and assembles received packets into datagram. The Data Link layer
works at the bit level and adds start/stop flags and bit error checking (CRC or parity)
to the packet frame. Error checking is at the bit level only, packets with errors are
discarded and a request for re-transmission is sent out. The Data Link layer is
concerned about bit sequence.

NETWORK LAYER:
The Network layer is concerned about the path through the network. It is
responsible for routing, switching and controlling the flow of information between
hosts. The Network layer converts the segments into smaller datagram that the
network can handle. The Network layer does not guarantee that the datagram will
reach its destination. The network hardware source and destination addresses are
added.

-4-
TRANSPORT LAYER:
In order for the data to be sent across the network, the file must be broken up
into usable small data segments (typically 512 - 18K bytes). The Transport layer
breaks up the file into segments for transport to the network and combines incoming
segments into a contiguous file. The Transport layer does this logically not physically;
it is done in software as opposed to hardware. The Transport layer provides error
checking at the segment level (frame control sequence). This checks that the datagram
are in the correct order and the Transport layer will correct out of order datagram. The
Transport layer guarantees an error-free host to host connection; it is not concerned
with the path between machines.

SESSION LAYER:
The Session layer manages the communications between the
workstation and network. The Session layer directs the information to the correct
destination and identifies the source to the destination. The Session layer identifies the
type of information as data or control. The Session layer manages the initial start-up
of a session and the orderly closing of a session. The Session layer also manages
Logon procedures and Password recognition.

-5-
PRESENTATION LAYER:
It converts local representation of data to its canonical form and vice
versa. The Presentation Layer also controls security at the file level. This provides file
locking and user security. It performs specific functions that are requested regularly
by applications. For example: encryption, ASCII to Unicode, Unicode to ASCII,
LSB-first representations to MSB-first representations

APPLICATION LAYER:
It provides network services to the end-users. Mail, ftp, telnet, DNS,
NIS, NFS are examples of network applications. Application layer protocols are
Application-dependent. It implements communication between two applications of
the same type. (Examples: FTP, HTTP, SMTP (email) etc…).

-6-
SUMMARY OF LAYERS:

DIFFERENCES BETWEEN ISO/OSI MODEL AND TCP/IP MODEL:

OSI Model Reference TCP/IP Model Reference


Service, interface and protocol are not Protocols in the OSI model are
clearly defined. For example, the only better hidden and can be replaced
Service,
real services offered by the Internet relatively easily as the
interface
layer are technology changes, which is
and protocol
- Send IP Packet one of the main objectives of
- Receive IP Packet layered protocols.
In this case, the protocols have
Because models were invented before
been invented before models, so
Functionalities protocols, functionalities put in each
the functionalities are perfectly
layer are not very optimized.
described.
Seven layers, Network (Internet),
Numbers of
Transport and Application layers being Only four layers.
layers
similar to TCP/IP
Both connectionless and connection- Only one mode in the network
Connectionless/
oriented communications are supported layer (connectionless) but both
Connection-
in the network layer, but only modes in the transport layer are
oriented
connection-oriented communication in supported, giving the users a
communication
the transport layer. choice.

CONCLUSION:
Thus the seven different layers of ISO/OSI model with their functionalities
were studied successfully.

-7-
2. UNIX SOCKET PROGRAMMING

INTRODUCTION:

In the client server architecture, a machine (referred as client) makes a request


to connect to another machine (called as server) for providing some service. The
services running on the server run on known ports (application identifiers) and the
client needs to know the address of the server machine and this port in order to
connect to the server. When we desire a communication between two applications
possibly running on different machines, we need sockets. Let us study the various
concepts behind UNIX socket programming.

SOCKET:

The server and client applications use various system calls to connect which
use the basic construct called socket. A socket is one end of the communication
channel between two applications running on different machines.

SOCKET COMMUNICATION DOMAINS:

Domain Description
AF_INET IPv4 Internet domain
AF_INET6 IPv6 Internet domain
AF_UNIX UNIX domain
AF_UNSPEC unspecified

(AF stands for Address family)

SOCKET TYPES:

Type Description
SOCK_DGRAM fixed-length, connectionless, unreliable messages.
(IPPROTO_UDP – protocol used for UDP)
SOCK_RAW datagram interface to IP (optional in POSIX.1)
SOCK_SEQPACKET fixed-length, sequenced, reliable, connection-oriented messages

SOCK_STREAM sequenced, reliable, bidirectional, connection-oriented byte


streams. (IPPROTO_TCP – protocol used for TCP)

ADDRESS FORMATS:

An address identifies a socket endpoint in a particular communication domain.


The address format is specific to the particular domain. The addresses are cast to a
generic sockaddr address structure:

-8-
struct sockaddr {
sa_family_t sa_family; /* address family */
char sa_data[14]; /* variable-length address */
};

Internet addresses are defined in <netinet/in.h>. In the IPv4 Internet domain


(AF_INET), a socket address is represented by a sockaddr_in structure:

struct sockaddr_in {
sa_family_t sin_family; /* address family */
in_port_t sin_port; /* port number */
struct in_addr sin_addr; /* IPv4 address */
unsigned char sin_zero[8]; /* filler */
};

BYTE ORDERING:

The byte order is a characteristic of the processor architecture, dictating how


bytes are ordered within larger data types, such as integers. Four common functions
are provided to convert between the processor byte order and the network byte order
for TCP/IP applications.

#include <arpa/inet.h>

uint32_t htonl(uint32_t hostint32); Returns: 32-bit integer in network byte order


("Host to Network Long" )
uint16_t htons(uint16_t hostint16); Returns: 16-bit integer in network byte order
("Host to Network Short")
uint32_t ntohl(uint32_t netint32); Returns: 32-bit integer in host byte order
("Network to Host Long" )
uint16_t ntohs(uint16_t netint16); Returns: 16-bit integer in host byte order
("Network to Host Short")

SYSTEM CALLS:

1. socket()
a. Synopsis:

#include<sys/types.h>
#include<sys/socket.h>
int socket(int domain, int type, int protocol);

b. Description: Creates a socket; Returns socket descriptor on success.


2. bind()
a. Synopsis:

#include<sys/socket.h>
int bind ( int sockfd , struct sockaddr *myaddr , int addrlen );

-9-
b. Description: Associates an address to a socket descriptor created by
socket.
3. listen()
a. Synopsis:

#include<sys/socket.h>
int listen(int skfd, int backlog);

b. Description: Announces willingness to accept connections; gives


queue size. (backlog is the maximum length of the queue for accepting
requests.)
4. connect()
a. Synopsis:

#include<sys/socket.h>
#include<netinet/in.h>
int connect(int skfd, struct sockaddr* addr, int addrlen);

b. Description: Signifies that the server is willing to accept connections


and thereby start communicating.
5. accept()
a. Synopsis:

#include<sys/socket.h>
int accept(int skfd, struct sockaddr* addr, int addrlen);

b. Description: Retrieves a connect request and convert that into a


connection.
6. close()
a. Synopsis:

#include<sys/socket.h>
int close(int skfd);

b. Description: Closes the connection. (A port can be reused only if it has


been closed completely.)

CONNECTION ORIENTED COMMUNICATION:

The connection is established through a dedicated link provided for the


communication. This type of communication is characterized by a high level of
reliability in terms of the number and the sequence of bytes.

Sequence of System Calls for Connection Oriented communication


The typical set of system calls on both the machines in a connection-oriented
setup is shown in Figure below.

- 10 -
CONNECTIONLESS COMMUNICATION:

Packets are sent at a time to a particular destination. For greater reliability, the
receiver may send an acknowledgement.

Sequence of System Calls for Connectionless Communication


The typical set of system calls on both the machines in a connectionless setup
is shown in Figure below.

CONCLUSION:

Thus the various concepts behind UNIX socket programming was studied
successfully.

- 11 -
3. BIT STUFFING AND CRC COMPUTATION

AIM:
To write and execute a C program that takes a binary input file as input and
performs Bit Stuffing and Cyclic Redundancy Check (CRC) Computation.

GENERAL ALGORITHM:

1. Start.
2. Read the input binary number and divisor from the input files.
(BIT STUFFING: FROM STEP 3 to STEP 4).
3. Insert a 0 after each consecutive five 1s.
4. Append a string of n 0s, where n is one less than the number of bits in the
divisor.
5. Display the bit stuffed data.
(CRC GENERATION: FROM STEP 5 TO STEP 8).
6. Divide the newly elongated data unit by the divisor (use binary division)
and the resultant remainder is called CRC of n bits.
7. Display the CRC value.
8. Replace the appended 0s by the CRC derived in Step 5.
9. Display the newly elongated data unit, along with CRC.
(CRC CHECKER: FROM STEP 9 TO STEP 15).
10. Divide the newly elongated data unit by the divisor (use binary division).
11. Display the remainder.
12. Replace the appended CRC by the newly generated remainder to the data
unit.
13. Display the newly elongated data unit.
(DESTUFFING).
14. Remove the appended remainder.
15. Remove the 0s inserted after each five consecutive 1s.
16. Display the resultant data unit which is same as the one taken as input.
17. Stop.

- 12 -
PROGRAM FOR BIT STUFFING AND CRC

//bitstuf.c
#include<stdio.h>
#include<conio.h>

void crc();
void display_rem();
int ip[20],n,i,j,k,fives=0,ndiv,div[20],t,inter[50],times=1,set=0;

void main()
{
FILE *fp,*fp1;
fp=fopen("INPUT.DAT","r");
fp1=fopen("DIV.DAT","r");
printf("\nINPUT BINARY NUMBER\t: ");
i=0;
do
{
fscanf(fp,"%d",&ip[i]);
printf("%d ",ip[i]);
i++;
}while(!feof(fp));
n=i;
printf("\n\nDIVISOR\t\t\t: ");
i=0;
do
{
fscanf(fp1,"%d",&div[i]);
printf("%d ",div[i]);
i++;
}while(!feof(fp1));
ndiv=i;
printf("\n");
fclose(fp);
fclose(fp1);
for(i=0;i<(n+set);i++)
{
if(ip[i]==1)
fives++;
else
fives=0;
if(fives==5)
{
fives=0;

for(j=(n+set);j>i;j--)
ip[j]=ip[j-1];
ip[i+1]=0;
set++;

- 13 -
}
}
j=0;
for(i=(n+set);j<(ndiv-1);i++,j++)
ip[i]=0;
printf("\nAFTER BIT STUFFING\t: ");
for(i=0;i<(n+ndiv+set-1);i++)
printf("%d ",ip[i]);
printf("\n");
crc();
display_rem();
printf("\nAFTER 1 CRC\t\t: ");
for(i=0;i<(n+ndiv+set-1);i++)
printf("%d ",ip[i]);
printf("\n");
times++;
crc();
display_rem();
printf("\nAFTER 2 CRC\t\t: ");
for(i=0;i<(n+ndiv+set-1);i++)
printf("%d ",ip[i]);
printf("\n");
fives=0;
printf("\nAFTER DESTUFFING\t: ");
for(i=0;i<(n+set);i++)
{
if(ip[i]==1)
fives++;
else
fives=0;
if(fives==5)
{
fives=0;
for(j=i+1;j<(n+set);j++)
ip[j]=ip[j+1];
}
}
for(i=0;i<n;i++)
printf("%d ",ip[i]);
printf("\n\n");
}

void crc()
{
for(i=0;i<(ndiv-1);i++)
inter[i]=ip[i];
j=0;
for(i=ndiv;i<=(ndiv+n+set-1);i++)
{
t=0;

- 14 -
if(i!=ndiv)
{
inter[k]=ip[i-1];
j++;
}
for(k=j;t<(ndiv-1);k++)
{
if(div[t]==inter[k])
inter[k]=0;
else
inter[k]=1;
t++;
}
}
}

void display_rem()
{
j=0;
printf("\nREMAINDER OF %d CRC\t: ",times);
t=k-(ndiv-1);
for(i=(n+set);j<(ndiv-1);i++,j++)
{
ip[i]=inter[t];
printf("%d ",inter[t]);
t++;
}
printf("\n");
}

- 15 -
INPUT FILES

INPUT.DAT

1111101

DIV.DAT

111

OUTPUT

INPUT BINARY NUMBER : 1 1 1 1 1 0 1

DIVISOR :111

AFTER BIT STUFFING :1111100100

REMAINDER OF 1 CRC :01

AFTER 1 CRC :1111100101

REMAINDER OF 2 CRC :00

AFTER 2 CRC :1111100100

AFTER DESTUFFING :1111101

[student@ws002 netlab]$

RESULT:
Thus the program for CRC and Bit Stuffing was worked out and the outputs
were generated and verified successfully.

- 16 -
4. SIMULATION OF ARP/RARP

AIM:
To develop a C program in Linux to simulate the Address Resolution Protocol
(ARP) and Reverse Address Resolution Protocol (RARP).

GENERAL ALGORITHM:

1. Start.
2. Specify the IP Addresses and Ethernet Addresses.
3. Create a LINUX Socket using socket () with proper arguments, which returns
a socket descriptor.
4. Set the port number for each of the three processes of arp-rarp programs.
5. Bind the path to the socket created, by calling the function bind () with proper
arguments.
6. Create a child process using fork ().
7. Receive the Ethernet or IP address request from the other processes.
8. Send the corresponding IP or Ethernet addresses reply to the requested
process.
9. Send the Ethernet or IP address request to the other processes.
10. Receive the corresponding IP or Ethernet address reply from the other
processes.
11. Terminate the connection using close ().
12. Stop.

- 17 -
PROGRAM FOR ARP / RARP

//arp1.c

#include<unistd.h>
#include<string.h>
#include<sys/types.h>
#include<fcntl.h>
#include<netinet/in.h>

main()
{
int sd,len=0,sz,i,k=0;
struct sockaddr_in s1,s2,s3;
char str[30]="",string[30]="",addr[30]="",status[10]="";
char
ip[10][20]={"127.0.0.1","127.0.0.2","127.0.0.3","127.0.0.4","127.0.0.5","127.0.0.6","
127.0.0.7","127.0.0.8","127.0.0.9","127.0.0.10"};
char
eth[10][20]={"12.32.45.0.0.1","12.32.45.0.0.2","12.32.45.0.0.3","12.32.45.0.0.4","12.
32.45.0.0.5","12.32.45.0.0.6","12.32.45.0.0.7","12.32.45.0.0.8","12.32.45.0.0.9","12.3
2.45.0.0.10"};
sd=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
s1.sin_port=htons(1101);
s1.sin_family=s2.sin_family=s3.sin_family=AF_INET;
s1.sin_addr.s_addr=s2.sin_addr.s_addr=s3.sin_addr.s_addr=htonl(INADDR_ANY);
s2.sin_port=htons(2202);
s3.sin_port=htons(3303);
if(bind(sd,(struct sockaddr*)&s1,sizeof(s1))<0)
{
printf("Bind error\n");
return 0;
}
sz=sizeof(s2);
if(fork()==0)
while(1)
{
fcntl(sd,F_SETFL,O_NONBLOCK);
recvfrom(sd,&str,30,0,(struct sockaddr*)&s2,&sz);
if(strcmp(str,"\0"))
{
k=2;
goto s;
}
recvfrom(sd,&str,30,0,(struct sockaddr*)&s3,&sz);
k=3;
s:if(strcmp(str,"\0"))
{
printf("%s\n",str);
strcpy(addr,str);

- 18 -
strcpy(str,"\0");
strncpy(str,addr,strlen(addr)-8);
str[strlen(addr)-8]='\0';
for(i=0;i<9;i++)
status[i]=addr[strlen(str)+i];
for(i=0;i<10;i++)
{
if(!strcmp(str,ip[i]))
{
strcpy(string,eth[i]);
strcat(string,"To Reply");
if(!strcmp(status," Request"))
{
if(k==2)
sendto(sd,&string,30,0,(struct sockaddr*)&s2,sizeof(s2));
else
sendto(sd,&string,30,0,(struct sockaddr*)&s3,sizeof(s3));
break;
}
}
if(!strcmp(str,eth[i]))
{
strcpy(string,ip[i]);
strcat(string,"To Reply");
if(!strcmp(status," Request"))
{
if(k==2)
sendto(sd,&string,30,0,(struct sockaddr*)&s2,sizeof(s2));
else
sendto(sd,&string,30,0,(struct sockaddr*)&s3,sizeof(s3));
break;
}
}
}
}
strcpy(str,"\0");
k=0;
}
else
while(1)
{
int flg=0;
scanf("%s",str);
for(i=0;i<10;i++)
{
if(!strcmp(str,ip[i]))
{
printf("%sTo Reply\n",eth[i]);
flg=1;
}

- 19 -
if(!strcmp(str,eth[i]))
{
printf("%sTo Reply\n",ip[i]);
flg=1;
}
}
if(flg)
continue;
strcat(str," Request");
sendto(sd,&str,30,0,(struct sockaddr*)&s2,sizeof(s2));
sendto(sd,&str,30,0,(struct sockaddr*)&s3,sizeof(s3));
}
close(sd);
}

//arp2.c

#include<sys/socket.h>
#include<unistd.h>
#include<string.h>
#include<sys/types.h>
#include<fcntl.h>
#include<netinet/in.h>

main()
{
int sd,len=0,sz,i,k=0;
struct sockaddr_in s1,s2,s3;
char str[30]="",string[30]="",addr[30]="",status[10]="";
char
ip[10][20]={"128.0.0.1","128.0.0.2","128.0.0.3","128.0.0.4","128.0.0.5","128.0.0.6","
128.0.0.7","128.0.0.8","128.0.0.9","128.0.0.10"};
char
eth[10][20]={"13.32.45.0.0.1","13.32.45.0.0.2","13.32.45.0.0.3","13.32.45.0.0.4","13.
32.45.0.0.5","13.32.45.0.0.6","13.32.45.0.0.7","13.32.45.0.0.8","13.32.45.0.0.9","13.3
2.45.0.0.10"};
sd=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
s1.sin_port=htons(2202);
s1.sin_family=s2.sin_family=s3.sin_family=AF_INET;
s1.sin_addr.s_addr=s2.sin_addr.s_addr=s3.sin_addr.s_addr=htonl(INADDR_ANY);
s2.sin_port=htons(3303);
s3.sin_port=htons(1101);
if(bind(sd,(struct sockaddr*)&s1,sizeof(s1))<0)
{
printf("Bind error\n");
return 0;
}
sz=sizeof(s2);
if(fork()==0)

- 20 -
while(1)
{
fcntl(sd,F_SETFL,O_NONBLOCK);
recvfrom(sd,&str,30,0,(struct sockaddr*)&s2,&sz);
if(strcmp(str,"\0"))
{
k=2;
goto s;
}
recvfrom(sd,&str,30,0,(struct sockaddr*)&s3,&sz);
k=3;
s:if(strcmp(str,"\0"))
{
printf("%s\n",str);
strcpy(addr,str);
strcpy(str,"\0");
strncpy(str,addr,strlen(addr)-8);
str[strlen(addr)-8]='\0';
for(i=0;i<9;i++)
status[i]=addr[strlen(str)+i];
for(i=0;i<10;i++)
{
if(!strcmp(str,ip[i]))
{
strcpy(string,eth[i]);
strcat(string,"To Reply");
if(!strcmp(status," Request"))
{
if(k==2)
sendto(sd,&string,30,0,(struct sockaddr*)&s2,sizeof(s2));
else
sendto(sd,&string,30,0,(struct sockaddr*)&s3,sizeof(s3));
break;
}
}
if(!strcmp(str,eth[i]))
{
strcpy(string,ip[i]);
strcat(string,"To Reply");
if(!strcmp(status," Request"))
{
if(k==2)
sendto(sd,&string,30,0,(struct sockaddr*)&s2,sizeof(s2));
else
sendto(sd,&string,30,0,(struct sockaddr*)&s3,sizeof(s3));
break;
}
}
}
}

- 21 -
strcpy(str,"\0");
k=0;
}
else
while(1)
{
int flg=0;
scanf("%s",str);
for(i=0;i<10;i++)
{
if(!strcmp(str,ip[i]))
{
printf("%sTo Reply\n",eth[i]);
flg=1;
}
if(!strcmp(str,eth[i]))
{
printf("%sTo Reply\n",ip[i]);
flg=1;
}
}
if(flg)
continue;
strcat(str," Request");
sendto(sd,&str,30,0,(struct sockaddr*)&s2,sizeof(s2));
sendto(sd,&str,30,0,(struct sockaddr*)&s3,sizeof(s3));
}
close(sd);
}

//arp3.c

#include<sys/socket.h>
#include<unistd.h>
#include<string.h>
#include<sys/types.h>
#include<fcntl.h>
#include<netinet/in.h>

main()
{
int sd,len=0,sz,i,k=0;
struct sockaddr_in s1,s2,s3;
char str[30]="",string[30]="",addr[30]="",status[10]="";
char
ip[10][20]={"129.0.0.1","129.0.0.2","129.0.0.3","129.0.0.4","129.0.0.5","129.0.0.6","
129.0.0.7","129.0.0.8","129.0.0.9","129.0.0.10"};
char
eth[10][20]={"14.32.45.0.0.1","14.32.45.0.0.2","14.32.45.0.0.3","14.32.45.0.0.4","14.

- 22 -
32.45.0.0.5","14.32.45.0.0.6","14.32.45.0.0.7","14.32.45.0.0.8","14.32.45.0.0.9","14.3
2.45.0.0.10"};
sd=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
s1.sin_port=htons(3303);
s1.sin_family=s2.sin_family=s3.sin_family=AF_INET;
s1.sin_addr.s_addr=s2.sin_addr.s_addr=s3.sin_addr.s_addr=htonl(INADDR_ANY);
s2.sin_port=htons(1101);
s3.sin_port=htons(2202);
if(bind(sd,(struct sockaddr*)&s1,sizeof(s1))<0)
{
printf("Bind error\n");
return 0;
}
sz=sizeof(s2);
if(fork()==0)
while(1)
{
fcntl(sd,F_SETFL,O_NONBLOCK);
recvfrom(sd,&str,30,0,(struct sockaddr*)&s2,&sz);
if(strcmp(str,"\0"))
{
k=2;
goto s;
}
recvfrom(sd,&str,30,0,(struct sockaddr*)&s3,&sz);
k=3;
s:if(strcmp(str,"\0"))
{
printf("%s\n",str);
strcpy(addr,str);
strcpy(str,"\0");
strncpy(str,addr,strlen(addr)-8);
str[strlen(addr)-8]='\0';
for(i=0;i<9;i++)
status[i]=addr[strlen(str)+i];
for(i=0;i<10;i++)
{
if(!strcmp(str,ip[i]))
{
strcpy(string,eth[i]);
strcat(string,"To Reply");
if(!strcmp(status," Request"))
{
if(k==2)
sendto(sd,&string,30,0,(struct sockaddr*)&s2,sizeof(s2));
else
sendto(sd,&string,30,0,(struct sockaddr*)&s3,sizeof(s3));
break;
}
}

- 23 -
if(!strcmp(str,eth[i]))
{
strcpy(string,ip[i]);
strcat(string,"To Reply");
if(!strcmp(status," Request"))
{
if(k==2)
sendto(sd,&string,30,0,(struct sockaddr*)&s2,sizeof(s2));
else
sendto(sd,&string,30,0,(struct sockaddr*)&s3,sizeof(s3));
break;
}
}
}
}
strcpy(str,"\0");
k=0;
}
else
while(1)
{
int flg=0;
scanf("%s",str);
for(i=0;i<10;i++)
{
if(!strcmp(str,ip[i]))
{
printf("%sTo Reply\n",eth[i]);
flg=1;
}
if(!strcmp(str,eth[i]))
{
printf("%sTo Reply\n",ip[i]);
flg=1;
}
}
if(flg)
continue;
strcat(str," Request");
sendto(sd,&str,30,0,(struct sockaddr*)&s2,sizeof(s2));
sendto(sd,&str,30,0,(struct sockaddr*)&s3,sizeof(s3));
}
close(sd);
}

- 24 -
OUTPUT

RUNNING arp1.c :

[student@ws002arp]$cc arp1.c
[student@ws002 arp]$./a.out
127.0.0.5
12.32.45.0.0.5To Reply
128.0.0.7
13.32.45.0.0.7To Reply
129.0.0.1 Request
12.32.45.0.0.6 Request
[student@ws002 arp]$

RUNNING arp2.c :

[student@ws002 arp]$cc arp2.c


[student@ws002 arp]$./a.out
128.0.0.7 Request
129.0.0.1
14.32.45.0.0.1To Reply
12.32.45.0.0.6 Request
[student@ws002 arp]$

RUNNING arp3.c :

[student@ws002 arp]$cc arp3.c


[student@ws002 arp]$./a.out
128.0.0.7 Request
129.0.0.1 Request
12.32.45.0.0.6
127.0.0.6To Reply
[student@ws002 arp]$

RESULT:
Thus the program to simulate ARP-RARP was worked out and the outputs
were generated successfully.

- 25 -
5. SIMULATION OF SLIDING WINDOW PROTOCOL

AIM:
To write and execute a C program in Linux to simulate the Sliding Window
Protocol.

GENERAL ALGORITHM FOR SLIDING WINDOW SERVER:

1. Start.
2. Create a LINUX Server Socket using socket () with proper arguments,
which returns a socket descriptor.
3. If socket descriptor < 0, then print the error message that socket can not be
created and exit.
4. Bind the path to the socket created, by calling the function bind () with
proper arguments.
5. If bind () returns a value < 0, then print the error message that can not bind
the socket with the path and exit.
6. Instruct the socket to listen for incoming connections from client
programs, by using listen () with proper arguments.
7. If listen () returns a value < 0, then print the error message that server can
not listen to the clients and exit.
8. Accept a connection from a client by using accept () with proper
arguments which returns another socket descriptor!
9. If the new descriptor < 0, then print the error message that server can not
accept any connection and exit.
10. Scan the string to be transmitted
11. Repeat the following steps until the length of the string:
a) The first four characters of the string is displayed and it is sent to
client, using write().
b) From the client receive whether to insert errors and if so, get the bit
position for inserting error.
c) If there’s error, retransmit from the bit error has inserted, to the client.
12. Terminate the connection using close ().
13. Stop.

- 26 -
GENERAL ALGORITHM FOR SLIDING WINDOW CLIENT:

1. Start.
2. Create a LINUX Socket using socket () with proper arguments, which
returns a socket descriptor.
3. If socket descriptor < 0, then print the error message that socket can not be
created and exit.
4. Initiate a connection to the server's socket by a call to connect ().

5. Repeat the following steps:

a) Receive the string (frame) from the server.


b) Display the string.
c) Get a choice whether to insert error or not.
d) If must insert error means, do the following steps:

i. Get the bit position to insert the error.


ii. Send the bit position to the server (write()).
iii. Read the string from the server and display it.

e) else, do the following:

i. Print that no error occurred.


ii. Send this detail to the server.

6. Terminate the connection using close ().


7. Stop.

- 27 -
PROGRAM FOR SLIDING WINDOW SERVER

//server.c

#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<string.h>
#define SERV_TCP_PORT 9888

int main ( )
{
char p[ 15 ],q[ 25 ],r[ 15 ],s[ 15 ];
int sockfd,newsockfd,clilen,i=1,j,k,n;
struct sockaddr_in caddr,saddr ;
char c;
if((sockfd=socket(AF_INET,SOCK_STREAM,0))<0)
perror( "Server:Socket Error");
bzero((char*)&saddr,sizeof(saddr));
saddr.sin_family=AF_INET ;
saddr.sin_addr.s_addr=htonl(INADDR_ANY);
saddr.sin_port=htons(SERV_TCP_PORT);
if((bind(sockfd,(struct sockaddr*)&saddr,sizeof(saddr)))<0)
perror("Server:Bind Error");
listen(sockfd,5);
clilen=sizeof(caddr);
if((newsockfd=accept(sockfd,(struct sockaddr*)&caddr,&clilen))<0)
perror("Server:Accept Error");
printf("Enter the string to be transmaitted\n");
scanf("%s",q);
for(i=0;i<strlen(q);i+=4)
{
strcpy(p,"");
for(j=0;j<4;j++)
{
if((i+j)==strlen(q))
{
for(k=0;k<3;k++)
if(((j+k)%4))
p[j+k]=' ';
else
{
j=j+k+1;
break;
}
}
p[j]=q[i+j];
}
p[j]='\0';

- 28 -
p[strlen(p)]='\0';
printf("\nThe Frame to be transmitted is %s",p );
write(newsockfd,p,strlen(p)+1);
read(newsockfd,s,5);
sscanf(s,"%d",&n);
if(n==-1)
puts("\nNo Error has occured!!!");
else
{
printf("\nAn Error has occured in position %d \n ",n );
for(j=n;j<4;j++)
r[j-n]=p[ j ];
r[j-n]='\0';
strcat(r," ");
n=strlen(r);
for(j=0;j<n-1;j++)
r[n+j]=s[n+j-1+i];
r[n+j]='\0';
puts("\nRetransmitting!!!");
write(newsockfd,r,strlen(r)+1);
}
}
write(newsockfd,p,strlen(p)+1);
puts("\nterminated!!!");
close(newsockfd);
close(sockfd );
}

- 29 -
PROGRAM FOR SLIDING WINDOW CLIENT

// client.c

#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<stdlib.h>
#include<string.h>
#define SERV_TCP_PORT 9888

int main()
{
char p[25],q[25];
int sockfd,flag=1,n,c,i;
struct sockaddr_in saddr;
FILE *fp;
bzero((char*)&saddr,sizeof(saddr));
saddr.sin_family= AF_INET;
saddr.sin_addr.s_addr=inet_addr("127.0.0.1");
saddr.sin_port=htons( SERV_TCP_PORT);
if((sockfd=socket(AF_INET,SOCK_STREAM,0))<0)
perror("Client::Socket Error");
if((connect(sockfd,(struct sockaddr*)&saddr,sizeof(saddr)))<0)
perror("Client::Connect Error");
while(1)
{
read(sockfd,q,25);
printf("the received Frame is %s\n ",q );
puts("Do u want to insert an error or not ( 1 - yes/0 - no)?");
scanf("%d",&c);
if(c)
{
puts("Enter the bit position you want to enter the error");
scanf("%d",&n);
sprintf(p,"%d",n);
write(sockfd,p,strlen(p)+1);
read(sockfd,q,25);
printf("The Retransmitted frame is %s \n ",q);
}
else
{
puts("No error");
n=-1;
sprintf(p,"%d",n);
write(sockfd,p,strlen(p)+1);
}
}

- 30 -
puts("Connection terminated");
close(sockfd);
return 0;
}

- 31 -
OUTPUT

SERVER SIDE:

[student@ws002 slide]$ cc server.c


[student@ws002 slide]$ ./a.out
Enter the string to be transmaitted
network

The Frame to be transmitted is netw


An Error has occured in position 3

Retransmitting!!!

The Frame to be transmitted is ork


No Error has occured!!!

terminated!!!

[student@ws002 slide]$

CLIENT SIDE:

[student@ws002 slide]$ cc client.c


[student@ws002 slide]$ ./a.out
The received Frame is netw
Do u want to insert an error or not ( 1 - yes/0 - no)?
1
Enter the bit position you want to enter the error
3
The Retransmitted frame is w
The received Frame is ork
Do u want to insert an error or not ( 1 - yes/0 - no)?
0
No error
[student@ws002 slide]$

RESULT:
Thus the program for the simulation of Sliding Window Protocol was worked
out and the outputs were generated and verified successfully.

- 32 -
6. CHAT APPLICATION

AIM:
To develop a C program in Linux for the Client - Server Application for Chat
in C.

GENERAL ALGORITHM FOR CHAT SERVER:

1. Start.
2. Create a LINUX Server Socket using socket () with proper arguments,
which returns a socket descriptor.
3. If socket descriptor < 0, then print the error message that socket can not be
created and exit.
4. Bind the path to the socket created, by calling the function bind () with
proper arguments.
5. If bind () returns a value < 0, then print the error message that can not bind
the socket with the path and exit.
6. Instruct the socket to listen for incoming connections from client
programs, by using listen () with proper arguments.
7. If listen () returns a value < 0, then print the error message that server can
not listen to the clients and exit.
8. Accept a connection from a client by using accept () with proper
arguments which returns another socket descriptor! The old descriptor is
still listening for new connections, but this new one is connected to the
client.
9. If the new descriptor < 0, then print the error message that server can not
accept any connection and exit.
10. Read the string from the client using read ().
11. Print the client message.
12. Send reply message to the client using write ().
13. Listen for the client message and read it from the client.
14. Repeat the steps from 10 to 12 until server or client says bye.
15. Terminate the connection using close ().
16. Stop.

- 33 -
GENERAL ALGORITHM FOR CHAT CLIENT:

1. Start.
2. Create a LINUX Socket using socket () with proper arguments, which
returns a socket descriptor.
3. If socket descriptor < 0, then print the error message that socket can not be
created and exit.
4. Initiate a connection to the server's socket by a call to connect ().

5. Send message to the server using write ().


6. Listen for the server message and read it from the server.
7. Print the server message.
8. Send message to the server using write ().
9. Repeat the steps from 5 to 7 until client says bye.
10. Terminate the connection using close ().
11. Stop.

- 34 -
PROGRAM FOR CHAT SERVER

//server.c

#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<unistd.h>
#define SER_PORT 8888

int main()
{
int a,sersock,newsock,n;
char str[25],str2[25];
struct sockaddr_in seraddr;
struct sockaddr_in cliinfo;
socklen_t esize=sizeof(cliinfo);
seraddr.sin_family=AF_INET;
seraddr.sin_port=htons(SER_PORT);
seraddr.sin_addr.s_addr=htonl(INADDR_ANY);
if((sersock=socket(AF_INET,SOCK_STREAM,0))<0)
{
error("SOCKET CANNOT BE CREATED\n");
exit(0);
}
else
printf("\n SOCKET CREATED SUCCESSFULLY\n");
if(bind(sersock,(struct sockaddr*)&seraddr,sizeof(seraddr))<0)
{
error("CANT BIND\n");
exit(0);
}

if(listen(sersock,1)<0)
{
error("CANT LISTEN");
exit(0);
}
else
printf("\n SERVER IS LISTENING\n");
if((newsock=accept(sersock,(struct sockaddr*)&cliinfo,&esize))<0)
{
error("CANT ACCEPT\n");
exit(0);
}
else
printf("\n CONNECTION ESTABLISHED WITH CLIENT\n");
read(newsock,str,sizeof(str));

- 35 -
do
{
printf("\n CLIENT:%s\n",str);
printf("\n SERVER:");
scanf("%s",&str2);
printf("\n");
write(newsock,str2,sizeof(str2));
listen(newsock,1);
read(newsock,str,sizeof(str));
n=strcmp(str,"bye");
a=strcmp(str2,"bye");
}
while(n!=0||a!=0);
close(newsock);
close(sersock);
return 0;
}

- 36 -
PROGRAM FOR CHAT CLIENT

//client.c

#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<unistd.h>
#define SER_PORT 8888

int main()
{
int a,disock;
char str[25],str2[25];
struct sockaddr_in diaddr;
diaddr.sin_family=PF_INET;
diaddr.sin_port=htons(SER_PORT);
diaddr.sin_addr.s_addr=htonl(INADDR_ANY);
if((disock=socket(PF_INET,SOCK_STREAM,0))<0)
{
perror("SOCKET\n");
exit(0);
}
else
printf("\n SOCKET CREATED SUCCESSFULLY\n");
if(connect(disock,(struct sockaddr*)&diaddr,sizeof(diaddr))<0)
{
perror("connect\n");
exit(0);
}
printf("\n CONNECTION ESTABLISHED WITH SERVER\n");
printf("\n CLIENT:");
scanf("%s",str);
printf("\n");
if(write(disock,str,sizeof(str))<0)
{
printf("\n DATA NOT SENT\n");
}
do
{
listen(disock,1);
read(disock,str,sizeof(str));
printf("\n SERVER:%s\n",str);
printf("\n CLIENT:");
scanf("%s",&str2);
printf("\n");

- 37 -
a=strcmp(str2,"bye");
write(disock,str2,sizeof(str2));
}
while(a!=0);
close(disock);
return 0;
}

- 38 -
OUTPUT

SERVER SIDE:

[student@ws002 chat]$ cc server.c


[student@ws002 chat]$ ./a.out

SOCKET CREATED SUCCESSFULLY

SERVER IS LISTENING

CONNECTION ESTABLISHED WITH CLIENT

CLIENT: Hi

SERVER: Hello

CLIENT: bye

SERVER: bye

[student@ws002 chat]$

CLIENT SIDE:

[student@ws002 chat]$ cc client.c


[student@ws002 chat]$ ./a.out

SOCKET CREATED SUCCESSFULLY

CONNECTION ESTABLISHED WITH SERVER

CLIENT:Hi

SERVER:Hello

CLIENT:bye

[student@ws002 chat]$

RESULT:
Thus the Client – server application for Chat was worked out and the output
was generated and verified successfully.

- 39 -
7. SIMULATION OF OSPF ROUTING PROTOCOL

AIM:
To write and execute a C program to simulate the OSPF Routing Protocol.

GENERAL ALGORITHM:

1. Start.
2. Open the input file in read mode and display the adjacent matrix.
3. Close the input file.
4. While the condition is true, repeat the following:

a) Get the source node for which the routing table is to be displayed.
b) For each node, do the following:

i. Search for the path with the minimum length.


ii. Print the destination, cost of the path from source to destination
and the Next router(node).

c) Get the option from the user to continue.


d) If option is not equal to ‘y’ or ‘Y’, break from the while loop.

5. Stop.

- 40 -
PROGRAM FOR OSPF PROTOCOL

//ospf.c

#include<stdio.h>
#include<conio.h>
#include<ctype.h>
#define MAX 30
#define UNVISITED -1
#define VISITED 1
#define INFINITY 32767
int adjMat[MAX][MAX],n;
void viewAdjMat();
void viewPathMat(int pm[MAX],int n,int len);
int searchPath(int src,int des,int pathmat[MAX],int *minLen);
typedef struct
{
int previous,len,status;
}node;
void main()
{
char ch,s,d;
int i,j,k,src,des,minLen,tot,pathMat[MAX];
FILE *f1;
n=7;
clrscr();
printf("\n The number of vertices of Weighted Graph: %d\n\n",n);
//scanf("%d",&n);
if((f1=fopen("input.txt","rt"))==NULL)
{
fprintf(stderr,"Cannot open input file.\n");
return;
}
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
fscanf(f1,"%d",&adjMat[i][j]);
fclose(f1);
printf("\n The adjacency matrix is . . .\n");
printf(“\n\t A B C D E F G \n”);
viewAdjMat();
while(1)
{
printf("\n\n Enter the Source Node:");
fflush(stdin);
scanf("%c",&s);
src=toupper(s)-64;
printf("\t DES \t COST \t NR\n");
for(i=1;i<=n;i++)
{
tot=searchPath(src,i,pathMat,&minLen);

- 41 -
printf("\t%c\t%d\t",i+64,minLen);
if(src==i)
printf("-\n");
else
printf("%c\n",pathMat[tot-1]+64);
}
printf("\n Do u want to continue (Y/N):");
ch=getche();
if(ch!='Y'&&ch!='y')
break;
}
}
void viewAdjMat()
{
int i,j;
printf("\n");
for(i=1;i<=n;i++)
{
printf("\n\n");
for(i=1;i<=n;i++)
{
printf("\n\n");
for(j=1;j<=n;j++)
{
if(j==1)
printf("%4c",i+64);
printf("%4d",adjMat[i][j]);
}
}
}
}
int searchPath(int src,int des,int pathMat[MAX],int *minLen)
{
node graph[MAX];
int i,k,min,tot=0,curVertex,newLen,u,v;
*minLen=0;
for(i=1;i<=n;i++)
{
graph[i].previous=0;
graph[i].len=INFINITY;
graph[i].status=UNVISITED;
}
graph[src].previous=0;
graph[src].len=0;
graph[src].status=VISITED;
curVertex=src;
while(curVertex!=des)
{
for(k=1;k<=n;k++)
{

- 42 -
if(adjMat[curVertex][k]>0&&graph[k].status==UNVISITED)
{
newLen=graph[curVertex].len+adjMat[curVertex][k];
if(newLen<graph[k].len)
{
graph[k].previous=curVertex;
graph[k].len=newLen;
}
}
}
min=INFINITY;
curVertex=0;
for(i=1;i<=n;i++)
if(graph[i].status==UNVISITED&&graph[i].len<min)
{
min=graph[i].len;
curVertex=i;
}
if(curVertex==0)
return 0;
graph[curVertex].status=VISITED;
}
while(curVertex!=0)
{
pathMat[++tot]=curVertex;
curVertex=graph[curVertex].previous;
}
for(i=tot;i>1;i--)
{
u=pathMat[i];
v=pathMat[i-1];
*minLen=*minLen+adjMat[u][v];
}
return(tot);
}

- 43 -
INPUT FILE

//INPUT.TXT

0 2 0 1 0 0 0

0 0 0 3 10 0 0

4 0 0 0 0 5 0

0 0 2 0 2 8 0

0 0 0 0 0 0 6

0 0 0 0 0 0 0

0 0 0 0 0 1 0

- 44 -
OUTPUT

The number of vertices of Weighted Graph: 7

The adjacency matrix is . . .

A B C D E F G

A 0 2 0 1 0 0 0

B 0 0 0 3 10 0 0

C 4 0 0 0 0 5 0

D 0 0 2 0 2 8 0

E 0 0 0 0 0 0 6

F 0 0 0 0 0 0 0

G 0 0 0 0 0 1 0

Enter the Source Node: A

DES COST NR
A 0 -
B 2 B
C 3 D
D 1 D
E 3 D
F 8 D
G 9 D

Do u want to continue (Y/N):N

RESULT:
Thus the program for the simulation of OSPF routing protocol was worked
out and the output (shortest path) was generated successfully.

- 45 -
8. DOMAIN NAMING SYSTEM

AIM:
To develop a Client, in C, that contacts a given DNS Server to resolve a given
host name.

GENERAL ALGORITHM FOR DNS SERVER:

1. Start.
2. Create a LINUX Server Socket using socket () with proper arguments,
which returns a socket descriptor.
3. Bind the path to the socket created, by calling the function bind () with
proper arguments.
4. Instruct the socket to listen for incoming connections from client
programs, by using listen () with proper arguments.
5. Accept a connection from a client by using accept () with proper
arguments which returns another socket descriptor! The old descriptor is
still listening for new connections, but this new one is connected to the
client.
6. Read the domain name from the client using read() with proper arguments.
7. Search the host address for the given domain name .
8. Write the host address to the client using write () with proper arguments.
9. Terminate the connection using close ().
10. Stop.

GENERAL ALGORITHM FOR DNS CLIENT:

1. Start.
2. Create a LINUX Socket using socket () with proper arguments, which
returns a socket descriptor.
3. Initiate a connection to the server's socket by a call to connect ().

4. Scan the domain name from the user and send it to the server.
5. Read the host address from the server and display it.
6. Stop.

- 46 -
PROGRAM FOR DNS SERVER

//server.c

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include<stdio.h>
#include<netdb.h>
#include<string.h>
#define TCP_SERV_PORT 7890

int main()
{
int listenfd,connfd;
socklen_t len;
struct sockaddr_in servaddr,cliaddr;
struct hostent *hp,tp;
char host[50],buff[100];
listenfd=socket(AF_INET,SOCK_STREAM,0);
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family=AF_INET;
servaddr.sin_port=htons(7TCP_SERV_PORT);
servaddr.sin_addr.s_addr=htonl(INADDR_ANY);
bind(listenfd,(struct sockaddr*)&servaddr,sizeof(servaddr));
listen(listenfd,10);
for(;;)
{
len=sizeof(cliaddr);
connfd=accept(listenfd,(struct sockaddr*)&cliaddr,&len);
read(connfd,host,sizeof(host));
printf("%s",host);
if((hp=gethostbyname(host))==NULL)
printf("cant get addr");
if(inet_ntop(AF_INET,hp->h_addr,buff,sizeof(buff))<=0)
printf("host address not available");
printf("%s",buff);
write(connfd,buff,strlen(buff)+1);
close(connfd);
}
return 0;
}

- 47 -
PROGRAM FOR DNS CLIENT

// client.c

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include<stdio.h>
#include<netdb.h>
#include<string.h>
#include<stdlib.h>

int main(int argc,char** argv)


{
socklen_t len;
struct sockaddr_in servaddr;
struct hostent tp;
char buff[100],host[50];
int sockfd;
sockfd=socket(AF_INET,SOCK_STREAM,0);
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family=AF_INET;
servaddr.sin_port=htons(7890);
servaddr.sin_addr.s_addr=inet_addr("127.0.0.1");
if(connect(sockfd,(struct sockaddr*)&servaddr,sizeof(servaddr))<0)
{
printf("connect error\n");
}
printf("Enter the domain name : ");
scanf("%s",host);
write(sockfd,host,strlen(host)+1);
if(read(sockfd,buff,sizeof(buff))<0)
{
printf("\nread error");
}
printf("\nThe host address %s",buff);
return 0;
}

- 48 -
OUTPUT

SERVER SIDE:

[student@ws002 dns]$ cc server.c


[student@ws002 dns]$ ./a.out

CLIENT SIDE

[student@ws002 dns]$ cc client.c


[student@ws002 dns]$ ./a.out

Enter the domain name : localhost.localdomain

The host address 127.0.0.1

[student@ws002 dns]$

RESULT:
Thus the Client that contacts a given DNS Server was developed and the given
host name was resolved successfully.

- 49 -
9. DOWNLOADING A FILE

AIM:
To write and execute a C program in Linux to download a file from a given
server.

GENERAL ALGORITHM FOR DOWNLOAD SERVER:

1. Start.
2. Create a LINUX Server Socket using socket () with proper arguments, which
returns a socket descriptor.
3. Bind the path to the socket created, by calling the function bind () with proper
arguments.
4. Instruct the socket to listen for incoming connections from client programs, by
using listen () with proper arguments.
5. Accept a connection from a client by using accept () with proper arguments
which returns another socket descriptor!
6. Read the filename from the client, using read().
7. Open the file that the client requested in read mode.
8. Write all the file contents to the client using write().
9. Close the file.
10. Terminate the connection using close ().
11. Stop.

- 50 -
GENERAL ALGORITHM FOR DOWNLOAD CLIENT:

1. Start.
2. Create a LINUX Server Socket using socket () with proper arguments, which
returns a socket descriptor.
3. Initiate a connection to the server's socket by a call to connect ().
4. Enter the file name to be downloaded.
5. Enter the filename in which the downloaded file must be saved.
6. Open the destination file name in write mode.
7. Send the file name to be downloaded to the server.
8. Read the file contents from the server and print it both in screen and
destination file.
9. Close the file.
10. Terminate the connection using close ().
11. Stop.

- 51 -
PROGRAM FOR SERVER

//server.c

#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<netdb.h>
#include<fcntl.h>
#include<stdlib.h>
#include<unistd.h>
#define SERV_TCP_PORT 8016
#define MAX 80
int main(int argc,char *argv[])
{
FILE *fp;
int sockfd,newsockfd,clength;
struct sockaddr_in serv_addr,cli_addr;
char s[MAX],t[MAX],str[MAX];
strcpy(t,"exit");
sockfd=socket(AF_INET,SOCK_STREAM,0);
serv_addr.sin_family=AF_INET;
serv_addr.sin_addr.s_addr=htonl(INADDR_ANY);
serv_addr.sin_port=htons(SERV_TCP_PORT);
bind(sockfd,(struct sockaddr*)&serv_addr,sizeof(serv_addr));
listen(sockfd,5);
clength=sizeof(cli_addr);
newsockfd=accept(sockfd,(struct sockaddr*)&cli_addr,&clength);
close(sockfd);
read(newsockfd,&str,MAX);
printf("FILE NAME REQUESTED :%s\n",str);
fp=fopen(str,"r");
while(fgets(s,79,fp)!=NULL)
write(newsockfd,&s,MAX);
write(newsockfd,&t,MAX);
fclose(fp);
close(newsockfd);
return 0;
}

- 52 -
PROGRAM FOR CLIENT

//client.c

#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<string.h>
#include<fcntl.h>
#include<stdlib.h>
#include<unistd.h>
#define SERV_TCP_PORT 8016
#define MAX 80
int main(int argc,char *argv[])
{
FILE *fp;
int sockfd;
char s[MAX],name[MAX],sendline[MAX],recvline[MAX+1];
struct sockaddr_in serv_addr;
strcpy(s,"exit");
sockfd=socket(AF_INET,SOCK_STREAM,0);
serv_addr.sin_family=AF_INET;
serv_addr.sin_addr.s_addr=INADDR_ANY;
serv_addr.sin_port=htons(SERV_TCP_PORT);
connect(sockfd,(struct sockaddr*)&serv_addr,sizeof(serv_addr));
printf("\n Enter the file name to be downloaded : ");
scanf("%s",sendline);
printf("\nEnter the destination file name : ");
scanf("%s",name);
fp=fopen(name,"w");
write(sockfd,sendline,MAX);
while(1)
{
read(sockfd,recvline,MAX);
if(strcmp(recvline,s)==0)
exit(0);
printf("%s",recvline);
fputs(recvline,fp);
}
fclose(fp);
close(sockfd);
return 0;
}

- 53 -
INPUT FILE

INPUT.DAT

This is an example for downloading a file.


Thank you.

OUTPUT

SERVER SIDE:

[student@ws002 download]$ cc server.c


[student@ws002 download]$ ./a.out

FILE NAME REQUESTED: input.dat

[student@ws002 download]$

CLIENT SIDE

[ student@ws002 download]$ cc client.c


[ student@ws002 download]$ ./a.out

Enter the file name to be downloaded: input.dat


Enter the destination file name : output.dat

This is an example for downloading a file.


Thank you.

[student@ws002 download]$

OUTPUT FILE

OUTPUT.DAT

This is an example for downloading a file.


Thank you.

RESULT:
Thus the program for downloading a file was worked out and requested file
was downloaded successfully.

- 54 -
10. DATA TRANSFER OVER RS232

AIM:
To write a C program to transfer data between systems over RS232.

GENERAL ALGORITHM FOR DATA TRANSFER OVER RS232:

1. Start.
2. Initialize the COM1 port.
3. Repeat the following:
3.1 Wait until get the data.
3.2 If data is available on the port, then do the following:
3.2.1 Input the data.
3.2.2 Display the data onto the screen.
3.3 If a key is pressed, do the following:
3.4 If it is esc key, then break.
3.5 Output the data.
4. Stop.

- 55 -
PROGRAM FOR DATA TRANSFER OVER RS232

// datatransfer.c
#include <bios.h>
#include <conio.h>

#define COM1 0
#define DATA_READY 0x100

#define SETTINGS ( 0x80 | 0x02 | 0x00 | 0x00)

int main(void)
{
int in, out, status;

bioscom(0, SETTINGS, COM1); /*initialize the port*/


cprintf("Data sent to you: ");
while (1)
{
status = bioscom(3, 0, COM1); /*wait until get a data*/
if (status & DATA_READY)
if ((out = bioscom(2, 0, COM1) & 0x7F) != 0) /*input a data*/
putch(out);
if (kbhit())
{
if ((in = getch()) == 27) /* ASCII of Esc*/
break;
bioscom(1, in, COM1); /*output a data*/
}
}
return 0;
}

- 56 -
OUTPUT

System1:

Data sent to you: I’m System 2.

System2:

Data sent to you: I’m System 1.

RESULT:
Thus the program to transfer data between two systems over RS232 was
worked out and outputs were generated successfully.

- 57 -
11. STUDY OF NS2 (NETWORK SIMULATOR VERSION 2)
SIMULATOR

INTRODUCTION:

NS2 stands for Network Simulator version 2. It is a discrete event simulator


for networking research. It works at packet level. NS2 simulator provides substantial
support to simulate bunch of protocols like TCP, UDP, FTP, HTTP and DSR. It
simulates both wired and wireless network. It is primarily UNIX based. It uses TCL
as its scripting language. NS2 is a standard experiment environment in research
community.

• Two languages: ( C++ and TCL )

C++ :
Æ Detailed protocol simulations require Systems Programming
Language.
Æ Byte manipulation, packet processing algorithm implementation.
Æ Runtime speed is important.
Æ Turn Around Time (run simulation, final bug, fix bug, recompile
and re-run) is slower.
TCL :
Æ Simulation of slightly varying parameters.
Æ Quickly exploring a number of scenarios.
Æ Iteration time (change the model and re-run) is more important.

Æ tcl Interpreter With Extents:

Fig. Architectural View of NS

USES OF NS2 SIMULATOR:

• Simulate different scenarios with existing protocols (TCP/UDP)


• Wired Routing protocols - Distance Vector and Link State (with the link state
patch)
• Ad-Hoc Routing protocols - DSR, AODV, TORA
• MAC protocols - 802.3, 802.11 (Wireless MAC)

- 58 -
• Scheduling disciplines - DropTail, RED, WFQ, DRR, LQD etc.
• Different traffic characterizations - Poisson, Exponential, Pareto etc.
• Modify NS-2 to implement your own versions of the above protocols or even
code totally new protocols
• Measurement of Statistics:

o Throughput, Delay, Jitter etc.


o Queue Monitoring, Drops at Queues.
o Literally all that you will need to know with your simulations.

• Graphic visualization - using “nam” (Network Animator)

PLATFORMS:

• Most UNIX and UNIX-like systems


o FreeBSD or *BSD
o Linux
o Sun Solaris
o HP, SGI
• Window 95/98/NT...
• Emulation only for FreeBSD for now

THE DOWNSIDE:

• Cannot capture all the nuances of the real world networks.


• Very large scale simulations take a lot of time – they may not be feasible
• Still in the research phase, and there may be many more bugs lurking out there
• Documentation not adequate
• No fancy user interface – often perceived as “unfriendly” (at least by people
who are new to ns-2)

HELLO WORLD EXAMPLE:

simple.tcl

set ns [new Simulator]

$ns at 1 “puts \“Hello World!\””

$ns at 1.5 “exit”

$ns run

% ns simple.tcl

Hello World!

- 59 -
RUNNING A SIMULATION:

• Design your simulation


• Build NS-2 scripts
• Run simulation program
• Analyze trace files
• Visualize your simulation (Animation)

DESIGN OUR SIMULATION

• Goal and expected results


• Network topology
o Node
o Link
• Specify Agents
o Protocol
• Traffic
• Simulation Scenario

A TCL SCRIPT EXAMPLE:

set ns [new Simulator]

set n0 [$ns node]

set n1 [$ns node]

n0

n1

set ftp [new Application/FTP]

$ftp attach-agent $tcp

$ns at 0.2 "$ftp start"

$ns at 1.2 ”exit"

$ns run

$ns duplex-link $n0 $n1 1.5Mb 10ms DropTail

set tcp [$ns create-connection TCP $n0 TCPSink $n1 0]

- 60 -
STEPS INVLOVED:

1. Run simulation program


2. Analyze trace file
3. Open trace.out in excel
4. Plot results in excel

RUN SIMULATION PROGRAM:

• Usage: ns file.tcl
• If the C++ source codes are modified, re-compilation is required
• What ns-2 does:

o Read the tcl file


o Run the simulation program
o Create trace files
o NAM (network animator) input files
o Statistics (you may need to write post processing scripts)

ANALYZE TRACE FILE:

• Use some scripts like awk or Perl, to filter the trace file
• Use Excel, xplot or xgraph to plot the results

RAW TRACE FILE:


+ 0.001 2 0 tcp 1000 ------- 0 2.0 1.0 0 0
- 0.001 2 0 tcp 1000 ------- 0 2.0 1.0 0 0
r 0.0028 2 0 tcp 1000 ------- 0 2.0 1.0 0 0
+ 0.0028 0 1 tcp 1000 ------- 0 2.0 1.0 0 0
- 0.0028 0 1 tcp 1000 ------- 0 2.0 1.0 0 0
r 0.009884 0 1 tcp 1000 ------- 0 2.0 1.0 0 0
+ 0.009884 1 0 ack 40 ------- 0 1.0 2.0 0 1
- 0.009884 1 2 ack 40 ------- 0 1.0 2.0 0 1
r 0.013128 1 0 ack 40 ------- 0 1.0 2.0 0 1
+ 0.013128 0 2 ack 40 ------- 0 1.0 2.0 0 1
- 0.013128 0 2 ack 40 ------- 0 1.0 2.0 0 1
r 0.01416 0 2 ack 40 ------- 0 1.0 2.0 0 1
+ 0.01416 2 0 tcp 1000 ------- 0 2.0 1.0 1 2
- 0.01416 2 0 tcp 1000 ------- 0 2.0 1.0 1 2

CONCLUSION:
Thus we have analyzed the several aspects of the NS2 Simulator in detail.

- 61 -
12. STUDY OF OPNET ( OPTIMIZED NETWORK ) SIMULATOR

INTRODUCTION
™ Optimized Network Engineering Tool
™ A powerful network simulation tool
o comprehensive development environment for modeling of
communication networks and distributed systems
o Accuracy and easy-of-use for network planner
™ System requirements
o Visual studio 6.0

MODELING OVERVIEW
BACKGROUNDS:
™ Object orientation
o OPNET Consists of objects, each with configurable sets of attribute
o Objects Belong to classes
™ Specialized in communication networks and information systems
™ Graphical specification
™ Flexibility to develop detailed custom models
o OPNET provides a flexible, high-level programming language with
extensive support
™ Automatic generation of simulations
o Automatically compiled with C programming language

TYPICAL APPLICATIONS OF OPNET:


™ Standards-based LAN and WAN performance modeling
™ Internetworking planning
™ Research and development in communications architectures and protocols
™ Distributed sensor and control networks
™ Mobil packet radio networks
™ Satellite networks

MODELING DOMAINS:

Domain Editor Modeling Focus

Network topology described in terms of subnetworks,


Network Project nodes, links, and geographical context.
Node internal architecture described in terms of
Node Node functional elements and data flow between them.
Behavior of process (protocols, algorithms,
applications), specified using finite state machines
Process Process
and extended high-level languages

- 62 -
OPNET MODEL HIERARCHY:

Re-Spec.

Initial Specification Data

Analysis

PROCESS DOMAIN
INTERRUPT DRIVEN EXECUTION:
™ Process are driven by events

– Internally or externally interrupted

STATE TRANSITION DIAGRAM:


™ Proto-C models consist of two basic components

– States and Transitions


™ A process has two executives
– Enter executive and Exit executive
™ Forced and Unforced States
– Forced State
• Proceeds without any event
– Unforced State
• Pauses between enter and exit executives and Waits for
interrupt to break

- 63 -
INITIAL STATE AND TRANSITIONS:
™ Initial state

– Must be designed in each process model


– Occur only once
™ Transitions
– Movement of a process from state to state and conditions under which
such changes may take places

(Condition)

/Executive
VARIABLES:
™ State variable

– Used to represent the information accumulated and retained by a


process
– Require a memory allocation of corresponding size that will last as
long as the process exists
™ Temporary variable
– Used to store information that doesn’t require persistency
– Doesn’t require additional memory
™ Global variable
– Used to provide a means for multiple processes in different modules

NODE DOMAIN
TYPICAL NODE MODELS:
™ Work station
o Generate and receive transfers of files or sparse packets and manage
several concurrent network connections
™ Packet switch
o Supports large numbers of incoming and outgoing data links and
performs packet routing at high speeds
™ Satellite terminal
o Generates and receives packets according to a CA protocol
™ Remote data sensor
o Acts as a simple source of packets, usually transmitting them in bursts
MODULE DEFINITION:
™ Processor modules
o Primary general-purpose building blocks of node models
o Can be specified by process model attribute
o Used to perform general processing of data packets
™ Queue modules
o Provide superset of the functionality of processor modules
o Are related to memories

- 64 -
™ Transmitter modules
o Serve as the outbound interface between packet streams in side a node
and communication links outside node
™ Receiver modules
o Serve as the inbound interface between communication links outside a
node and packet streams inside the node

OSI/OPNET LAYERING ANALOGY:

NETWORK DOMAIN
CONCEPTS:

™ Define the overall scope of a system to be simulated


™ Size and scope of the networks modeled can range simple to complex

- 65 -
NETWORK OBJECTS:
™ Sub networks
o Provide a powerful mechanism to manipulate complex networks
structures and to break down the system’s complexity through
abstractions
o Have Fixed, mobile, satellite types
™ Communication nodes
o Exits within a sub network and represents a network device with a
wide range of possible capabilities
o Determined by node models
o Have fixed, mobile, and satellite types
™ Communication links
o Allow communication of information between nodes in the form of
structured message called packets
o Simplex, duplex point to point, bus and taps.

CONCLUSION:
Thus we have analyzed the several aspects of the OPNET Simulator in detail.

- 66 -
APPENDIX

™ Computer network -> communication system for connecting end systems.


-> a connected set of autonomous computers.

™ Program -> executable file


™ Process -> program that is being executed by computer’s OS
™ Server -> process that is waiting to be contacted by a client process’s that
server can do something for client
™ Internet / IP Address -> 32 bit number, that is, 4 bytes; used to identify the
system.
™ Hardware / Ethernet address -> 48 bit number, i.e., 6 bytes; imprinted on
Network Interface Card (NIC)
™ Port number -> 16 bit number; used to identify the particular server process.
™ Socket address comprises of the port number and IP address
™ When a C program is compiled, it generates a.out file.
™ TCP ->Transmission Control Protocol. (used in Transport Layer)
->A connection oriented protocol that provides a reliable, full-duplex,
byte stream for a user process. Most Internet application programs use TCP.
Since TCP uses IP the entire internet protocol suite is often called the TCP/IP
protocol family.
™ UDP ->User Datagram Protocol. (used in Transport Layer)
->A connectionless protocol for user processes. Unlike TCP, which is a
reliable protocol, there is no guarantee that UDP datagram ever reach their
intended destination.
™ ICMP ->Internet Control Message Protocol.
->The protocol to handle error and control information between
gateways and hosts.
™ IP -> Internet Protocol. (used in Network Layer)
->It provides the packet delivery service for TCP, UDP and ICMP.
™ TELNET -> provides a Remote Login. It allows an interactive user on a client
system to start login session a remote system. Once a login session is
established, the client process passes the user’s keystrokes to the server.

- 67 -
S.No Header file Purpose / System calls / structure
1 <sys/socket.h> Defines various socket functions.
struct sockaddr.

send(), sendto(), receive(), receivefrom()


2 <sys/types.h> Defines numerous data types using c language typedef construct
3 <netinet/in.h> struct sockaddr_in
htonl(),htons(),bind()
4 <netdb.h> struct hostent.
5 <arpa/inet.h> inet_ntoa(struct in_addr inaddr) , inet_addr(char *ptr).
6 <fcntl.h> Defines UNIX / LINUX system calls for I/O
open(),creat(),read(),write(),fcntl()

S.No System Calls Purpose


1 fcntl() Changes the properties of a file that is already opened.
2 bzero(char *dest, int Writes the specified number of null bytes to the specified
nbytes) destination.
3 inet_ntoa() Converts a 32-bit Internet Address to a string in dotted decimal
notation.
4 htonl() Converts host to network long integer. (long integer – 32bits).
5 htons() Converts host to network short integer. (short integer – 16 bits).
6 gethostbyname() Returns a pointer to hostent structure.
7 socket() Creates endpoint
8 bind() Binds address
9 listen() Specify queue
10 accept() Waits for connection
11 connect() Connects to the sever
12 fork() Creates a copy of the process that was executing.
->process that executed the fork =>parent process
->new process =>child process

- 68 -
CRC AND BIT STUFFING
™ CRC stands for Cyclic Redundancy Check; most powerful error detector
which is based on Binary division.
™ The redundancy bits used by CRC are derived by dividing the data unit by a
predetermined divisor; the remainder is CRC.
™ To be valid CRC must have two qualities:
• CRC must have exactly one bit less than divisor.
• Appending CRC to the end of the data string must make the
resulting bit sequence exactly divisible by the divisor.
™ Polynomial Form:
o The divisor can also be represented as polynomial.
o Ex: x7 + x5 + x2+ x + 1 == > 10100111.
™ Bit stuffing is the process of adding an extra 0 to prevent the receiver from
mistaking the data for a flag.

SIMULATION OF SLIDING WINDOW PROTOCOL


™ The basic idea of sliding window protocol is that both sender and receiver
keep a ``window'' of acknowledgment.
™ The sender keeps the value of expected acknowledgment; while the receiver
keeps the value of expected receiving frame.
™ When it receives an acknowledgment from the receiver, the sender advances
the window. When it receives the expected frame, the receiver advances the
window.

SIMULATION OF ARP/RARP
™ ARP -> Address Resolution Protocol.
-> It maps an Internet address into a hardware address. (used in
network layer)
™ RARP ->Reverse Address Resolution Protocol.
-> it maps a hardware address into an Internet Address. (used in
network layer)

- 69 -
CHAT APPLICATION
™ Sockets provide point-to-point, two-way communication between two
processes.
™ A socket is an endpoint of communication to which a name can be bound.
™ A socket domain is an abstraction that provides an addressing structure
and a set of protocols.
™ Sockets connect only with sockets in the same domain.

SIMULATION OF OSPF ROUTING PROTOCOL


™ Open Shortest Path First (OSPF) is a TCP/IP internet routing protocol.
™ OSPF is classified as an Interior Gateway Protocol (IGP).
™ This means that it distributes routing information between routers belonging
to a single Autonomous System.
™ The OSPF protocol is based on link-state or SPF technology.
™ Interior Gateway Protocol :
The routing protocol spoken by the routers belonging to an
Autonomous system. Abbreviated as IGP. Each Autonomous System has a single
IGP. Separate Autonomous Systems may be running different IGPs.
™ OSPF (open shortest path first) is a well known real-world implementation of
Dijkstra's algorithm used in internet routing.
™ Dijkstra's algorithm is a greedy algorithm that solves the single-source
shortest path problem for a directed graph with nonnegative edge weights.

DOMAIN NAME SYSTEM


™ Domain Name System (DNS) is a Client-Server Application that identifies
each host on the Internet with a unique user-friendly name.
™ On the Internet, DNS associates various sorts of information with so-called
domain names; most importantly, it serves as the "phone book" for the
Internet: it translates human-readable computer hostnames, e.g.
en.wikipedia.org, into the IP addresses that networking equipment needs for
delivering information.

- 70 -
DOWNLOADING A FILE
™ HyperText Transfer Protocol (HTTP) is a communications protocol used to
transfer or convey information on the World Wide Web.
™ Its original purpose was to provide a way to publish and retrieve HTML
hypertext pages.
™ HTTP is a request/response protocol between clients and servers.
™ File Transfer Protocol (FTP), a standard Internet protocol is commonly used
to download programs and other files to your computer from other servers.

DATA TRANSFER OVER RS232


™ RS232 is a popular communications protocol for connecting modems and data
acquisition devices to computers.

fig.1 connections of the Null modem using RS-232D connecter

Fig 2. Loop-back plug connection


™ RS232 is a popular communications protocol for connecting modems
and data acquisition devices to computers.
™ RS232 devices can be plugged straight into the computer's serial port
(also known as the COM or Comms port).

- 71 -
™ Examples of data acquisition devices include GPS receivers, electronic
balances, data loggers, temperature interfaces and other measurement
instruments.

™ bioscom(int cmd, char abyte, int port) Æ used in the serial


communication using RS-232 connecter.
cmd: The I/O operation to be performed.
cmd cmd(_bios_serialcom) Action
(bioscom)
0 _COM_INIT Initialise the parameters to the port
1 _COM_SEND Send the character to the port
2 _COM_RECEIVE Receive character from the port
3 _COM_STATUS Returns rhe current status of the communication port
port: port to which data is to be sent or from which data is to be
read. 0: COM1
1: COM2
2: COM3
abyte: When cmd =2 or 3 (_COM_SEND or _COM_RECEIVE) parameter abyte is
ignored.

- 72 -

You might also like