NO:1
DATE:
AIM:
To write a C program to perform stop and wait protocol and sliding window protocol.
ALGORITHM:
1.Start the program.
2.Get the frame size from the user
3.To create the frame based on the user request.
4.To send frames to server from the client side.
5.If your frames reach the server it will send ACK signal to client otherwise it will
send NACK signal to client.
6.Stop the program
PROGRAM :STOP AND WAIT PROTOCOL:
#include<stdio.h>
#define MAXSIZE 100
typedef struct
{
unsigned char data[MAXSIZE];
}packet;
typedef enum{data,ack}frame_kind;
typedef struct
{ frame_kind kind;
int sq_no;
int ack;
packet info;
}frame;
typedef enum{frame_arrival}event_type;
typedef enum{true_false}boolean;
void frame_network_layer(packet *p)
{ printf("\n from network arrival");}
void to_physical_layer(frame *f)
{ printf("\n to physical layer");}
void wait_for_event(event_type *e)
{ printf("\n waiting for event n");}
void sender(void)
{ frame s;
packet buffer;
event_type event;
printf("\n ***SENDER***");
frame_network_layer(&buffer);
s.info=buffer;
to_physical_layer(&s);
wait_for_event(&event);}
void from_physical_layer(frame *f)
{ printf("from physical layer");}
void to_network_layer(packet *p)
{ printf("\n to network layer");}
void receiver(void)
{ frame r,s;
event_type event;
printf("\n ***RECEIVER***");
wait_for_event(&event);
from_physical_layer(&r);
to_network_layer(&r.info);
to_physical_layer(&s);}
main()
{ sender();
receiver(); }
OUTPUT:
//SLIDINGSER.C SERVER:
#include<sys/socket.h>
#include<netinet/in.h>
#include<netdb.h>
#include<sys/types.h>
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
#define MAX 100
# define PORT 7386
int main(int argc,char **argv)
{
int sfd,cfd,slen,clen,i,ch,len;
FILE *fp;
char buff[MAX],filename[MAX];
struct sockaddr_in servaddr,cliaddr;
if((sfd=socket(AF_INET,SOCK_STREAM,0))<0)
{ perror("Socket not created\n");
exit(0); }
slen=sizeof(servaddr);
memset(&servaddr,slen,0);
servaddr.sin_addr.s_addr=INADDR_ANY;
servaddr.sin_port=htons(PORT);
servaddr.sin_family=AF_INET;
if(bind(sfd,(struct sockaddr *)&servaddr,slen)<0)
{ printf("Bind failed\n");
close(sfd);
exit(1); }
printf("SERVER SOCKET BINDED\n");
listen(sfd,5);
printf("SERVER SOCKET listened\n");
len=sizeof(cliaddr);
if((cfd=accept(sfd,(struct sockaddr *)&cliaddr,&len))<0)
{
printf("Accept failed\n");
close(sfd);
exit(1);
}
printf("SERVER Socket accepted connection with a Client\n");
bzero(filename,MAX);
if(recv(cfd,filename,sizeof(filename),0)<0)
{
printf("Did not receive the filename");
close(sfd);
close(cfd);
exit(1);
}
for(i-0;i<MAX;i++)
if(filename[i]=='\n'||filename[i]=='\r')
{
filename[i]='\0';
break;
}
#include<sys/socket.h>
#include<netinet/in.h>
#include<sys/types.h>
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
#define MAX 100
#define PORT 7386
int main(int argc,char *argv[])
{
int ct,sockfd;
int sfd,slen,clen,bufsize;
char buff[MAX];
FILE *fp;
struct sockaddr_in serv,cliaddr;
sockfd=socket(AF_INET,SOCK_STREAM,0);
if(sockfd<1)
{
perror("Socket error");
exit(0);
}
printf("CLIENT SOCKED CREATED");
bzero(&serv,sizeof(serv));
serv.sin_family=AF_INET;
serv.sin_port=htons(PORT);
serv.sin_addr.s_addr=inet_addr(argv[1]);
if(connect(sockfd,(struct sockaddr *)&serv,sizeof(serv))<0)
{
printf("ERROR IN CONNECT");
exit(1);
}
printf("CLIENT SOCKET CONNECTED");
printf("\nEnter filename");
scanf("%s",buff);
send(sockfd,buff,sizeof(buff),0);
do
{
bzero(buff,sizeof(buff));
recv(sockfd,buff,MAX,0);
if(strncmp(buff,"OVER",3)==0)
break;
printf("\nReceived:%s, sending ACK...\n",buff);
send(sockfd,"ACK",4,0);
}
while(1);
close(sockfd);
printf("\nReceived and signal(OVER) terminating\n");
return 0;
}
OUTPUT:
//SERVER
rmk@rmk-desktop:~/NWLAB/SLIDING$ cc slidingser.c
rmk@rmk-desktop:~/NWLAB/SLIDING$ ./a.out
SERVER SOCKET BINDED
SERVER SOCKET listened
SERVER Socket accepted connection with a Client
File requested: sample.txt
Sending:GReceived ACK...
Sending:OReceived ACK...
Sending:OReceived ACK...
Sending:DReceived ACK...
Sending: Received ACK...
Sending:DReceived ACK...
Sending:AReceived ACK...
Sending:YReceived ACK...
Sending:
Received ACK...
Sending: OVERrmk@rmk-desktop:~/NWLAB/SLIDING$
//CLIENT
rmk@rmk-desktop:~/NWLAB/SLIDING$ cc slidingcli.c
rmk@rmk-desktop:~/NWLAB/SLIDING$ ./a.out 127.0.0.1
CLIENT SOCKED CREATEDCLIENT SOCKET CONNECTED
Enter filenamesample.txt
Received:G, sending ACK...
Received:O, sending ACK...
Received:O, sending ACK...
Received:D, sending ACK...
Received: , sending ACK...
Received:D, sending ACK...
Received:A, sending ACK...
Received:Y, sending ACK...
Received:, sending ACK...
Received and signal(OVER) terminating
rmk@rmk-desktop:~/NWLAB/SLIDING$
RESULT:
Thus the program to implement layer2 sliding window protocol has been implemented
successfully.
EX. NO: 2
DATE:
A) SOCKET
AIM:
To create a new socket by using the socket function.
ALGORITHM:
STEP 1: Start the program.
STEP 2: Declare the socket header file sys/ socket.h.
STEP 3: Declare sockfd to store the field descriptor value.
STEP 4: Define the FAMILY, TYPE and PROTOCOL to SOCKET function
Store it into sockfd.
STEP 5: If sockfd value is -1 means then Socket is not created.
Otherwise Socket is created and displays the socket field descriptor
Value.
STEP 6: Stop the program.
CODING:
#include<sys/socket.h>
#include<stdio.h>
main()
{
int fd1,fd2,fd3,fd4;
fd1=socket(AF_INET,SOCK_STREAM,0);
fd1=socket(AF_INET,SOCK_STREAM,1);
fd1=socket(AF_INET,SOCK_DGRAM,0);
fd1=socket(AF_KEY,SOCK_DGRAM,0);
if(fd1==-1)
printf(\n The TCP socket is not created and contain some error);
else
printf(\n The TCP socket is created and the value for fd is %d,fd1);
if(fd2==-1)
printf(\n The TCP socket is not created and contain some error);
else
printf(\n The TCP socket is created and the value for fd is %d,fd2);
if(fd3==-1)
printf(\n The UDP socket is not created and contain some error);
else
printf(\n The UDP socket is created and the value for fd is %d,fd3);
if(fd4==-1)
printf(\n The socket is not created and contain some error);
else
CODING:
#include<stdio.h>
#include<sys/socket.h>
#include<netinet/in.h>
#define PORT 450
#define queuelen 5
int main()
{
int fd,b,l;
struct sockaddr_in myaddr;
fd=socket(AF_INET,SOCK_STREAM,0);
if(fd==-1)
printf("\n Socket creation error");
else
{
printf("\n Socket Created");
printf("Socket Field Description Value is %d",fd);
}
myaddr.sin_family=AF_INET;
myaddr.sin_port=PORT;
myaddr.sin_addr.s_addr=INADDR_ANY;
b=bind(fd,(struct sockaddr*)&myaddr,sizeof(struct sockaddr));
if(b==-1)
printf("\n Socket Binding Error");
else
printf("\n Socket is binding at port %d",PORT);
l=listen(fd,queuelen);
if(l==-1)
printf("Socket Listen Error");
else
printf("\n Server is in Listener Mode");
return 0;
}
OUTPUT:
Socket Created.
Socket Field Description Value is 3
Socket is binding at port 450
Server is in Listener Mode
RESULT:
Thus the program of Socket Listen was written, executed and verified
successfully.
{
if((num=read(sfd,buff,sizeof(buff)))==0)
return;
write(sfd,buff,num);
}
}
//itercli.c -- Echo client
#include<stdio.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<string.h>
#include<unistd.h>
#define PORT 7783
void str_cli(FILE *fp,int sfd);
int main(int argc,char *argv[])
{
int sockfd;
struct sockaddr_in serv;
char buff[30];
printf("ECHO CLIENT...\nid---");
sockfd=socket(AF_INET,SOCK_STREAM,0);
printf("%d",sockfd);
if (sockfd ==0)
printf("Socket Creation Error");
printf("Socket created");
memset(&serv,0,sizeof(serv));
serv.sin_family=AF_INET;
serv.sin_port=htons(PORT);
serv.sin_addr.s_addr=inet_addr(argv[1]);
if(connect(sockfd,(struct sockaddr *)&serv,sizeof(serv))<0)
printf("ERROR IN CONNECT");
str_cli(stdin,sockfd);
close(sockfd);
return;
}
void str_cli(FILE *fp,int sockfd)
{
char sendbuff[30],recvbuff[30];
printf("ENTER A STRING TO ECHO");
if(fgets(sendbuff,sizeof(sendbuff),fp)!=NULL)
{
write(sockfd,sendbuff,strlen(sendbuff));
if(read(sockfd,recvbuff,sizeof(recvbuff))==0)
printf("Error in writing.");
printf("\nSTRING ECHOED FROM SERVER : %s",recvbuff);
}
}
OUTPUT:
//SERVER
rmk@rmk-desktop:~/NWLAB/ITERATIVE$ cc iterserv.c
rmk@rmk-desktop:~/NWLAB/ITERATIVE$ ./a.out
Message Received and Echoed : Good
//CLIENT
rmk@rmk-desktop:~/NWLAB/ITERATIVE$ cc itercli.c
rmk@rmk-desktop:~/NWLAB/ITERATIVE$ ./a.out 127.0.0.1
ENTER THE STRING TO ECHO :Good
Good
rmk@rmk-desktop:~/NWLAB/ITERATIVE$
TCP ECHO CLIENT SERVER - CONCURRENT MODEL:
//conserv.c -- Concurrent Echo server using fork()
#include<stdio.h>
#include<time.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<sys/socket.h>
#include<string.h>
#include<unistd.h>
#define PORT 7785
void str_echo(int sockfd);
int main(int argc, char *argv[])
{
char buffer[30];
int sockfd,connfd,a,len;
time_t sec;
struct sockaddr_in servaddr,cliaddr;
printf("ECHO SERVER .....\n\n");
sockfd=socket(AF_INET,SOCK_STREAM,0);
if(sockfd==-1)
printf("ERROR CREATING SOCKET!");
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family=AF_INET;
servaddr.sin_port=htons(PORT);
servaddr.sin_addr.s_addr=htonl(INADDR_ANY);
printf("Socket created");
memset(&serv,0,sizeof(serv));
serv.sin_family=AF_INET;
serv.sin_port=htons(PORT);
serv.sin_addr.s_addr=inet_addr(argv[1]);
if(connect(sockfd,(struct sockaddr *)&serv,sizeof(serv))<0)
printf("ERROR IN CONNECT");
str_cli(stdin,sockfd);
close(sockfd);
return;
}
void str_cli(FILE *fp,int sockfd)
{
char sendbuff[30],recvbuff[30];
printf("ENTER A STRING TO ECHO");
if(fgets(sendbuff,sizeof(sendbuff),fp)!=NULL)
{
write(sockfd,sendbuff,strlen(sendbuff));
if(read(sockfd,recvbuff,sizeof(recvbuff))==0)
printf("Error in writing.");
printf("\nSTRING ECHOED FROM SERVER : %s",recvbuff);
}
}
OUTPUT:
rmk@rmk-desktop:~/NWLAB/CONCURRENT$ cc conserv.c
rmk@rmk-desktop:~/NWLAB/CONCURRENT$ ./a.out
Message Received and Echoed : Hello
Message Received and Echoed : Bye
[5]+ Stopped
./a.out
rmk@rmk-desktop:~/NWLAB/CONCURRENT$
//client 1
rmk@rmk-desktop:~/NWLAB/CONCURRENT$ cc concli.c
rmk@rmk-desktop:~/NWLAB/CONCURRENT$ ./a.out 127.0.0.1
ENTER THE STRING TO ECHO :Hello Hello
rmk@rmk-desktop:~/NWLAB/CONCURRENT$
//client 2
rmk@rmk-desktop:~/NWLAB/CONCURRENT$ cc concli.c
rmk@rmk-desktop:~/NWLAB/CONCURRENT$ ./a.out 127.0.0.1
ENTER THE STRING TO ECHO :Bye Bye
rmk@rmk-desktop:~/NWLAB/CONCURRENT$
RESULT:
Thus the program of Socket Listen was written, executed and verified
successfully.
EX.NO.:3
DATE:
AIM
To write a program to implementation of Address Resolution Protocol/Reverse Address
Resolution Protocol.
ALGORITHM
1. Start the program
2. Declare the variables using arrays.Calculate the Ethernet address and IP address using for
loop.
3. Calculate the address resolution protocol value.
4. Display the server IP address.
5. If the client systems are connected to server then display the Ethernet/IP address, otherwise
display No response.
6. Compile and execute the program.
7. Stop the program.
CODING
ARP SERVER
#include<stdio.h>
#include<sys/types.h>
#include<sys/shm.h>
#include<string.h>
main()
{
intshmid, a, i;
char *ptr, *shmptr;
shmid=shmget(3000,10,IPC_CREAT | 0666);
shmptr=shmat(shmid,NULL,0);
ptr=shmptr;
for(i=0;i<3;i++)
{
puts("enter the mac");
scanf("%s",ptr);
a=strlen(ptr);
printf("string length:%d",a);
ptr[a]= ' ' ;
puts("enter ip");
ptr=ptr+a+1;
scanf("%s",ptr);
ptr[a]='\n' ;
ptr= ptr+a+1;
}
ptr[strlen(ptr)]= '\0';
OUTPUT:
the arp table is
a.b.c.d 1.2.3.4
e.f.g.h 5.6.7.8
i.j.k.l 9.1.2.3
1.ARP
2.RARP
3.EXIT
enter your choice: 1
enter ip address: 1.2.3.4
mac addr is a.b.c.d
enter your choice:2
enter mac address: e.f.g.h
ipaddr is 5.6.7.8
RESULT
Thus the program for Address Resolution Protocol/Reverse Address Resolution Protocol
has been performed and verified successfully.
EX-NO. 4.
DATE:
AIM:
To Write The java program for simulating ping and traceroute commands
ALGORITHM:
1.Start the program.
2.Get the frame size from the user
3.To create the frame based on the user request.
4.To send frames to server from the client side.
5.If your frames reach the server it will send ACK signal to client otherwise it will
send NACK signal to client.
6.Stop the program
PROGRAM:
//pingclient.java
import java.io.*;
import java.net.*;
import java.util.Calendar;
class pingclient
{
public static void main(String args[])throws Exception
{
String str;
int c=0;
long t1,t2;
Socket s=new Socket("127.0.0.1",5555);
DataInputStream dis=new DataInputStream(s.getInputStream());
PrintStream out=new PrintStream(s.getOutputStream());
while(c<4)
{
t1=System.currentTimeMillis();
str="Welcome to network programming world";
out.println(str);
System.out.println(dis.readLine());
t2=System.currentTimeMillis();
System.out.println(";TTL="+(t2-t1)+"ms");
c++;
}
s.close();
}
}
//pingserver.java
import java.io.*;
import java.net.*;
import java.util.*;
import java.text.*;
class pingserver
{
public static void main(String args[])throws Exception
{
ServerSocket ss=new ServerSocket(5555);
Socket s=ss.accept();
int c=0;
while(c<4)
{
DataInputStream dis=new DataInputStream(s.getInputStream());
PrintStream out=new PrintStream(s.getOutputStream());
String str=dis.readLine();
out.println("Reply from"+InetAddress.getLocalHost()+";Length"+str.length());
c++;
}
s.close();
}
}
Output :
Result:
Thus the program was implementing to simulating ping and traceroute commands.
EX NO: 5
DATE:
AIM:
To write a java program for socket for HTTP for web page upload and download .
ALGORITHM:
1.Start the program.
2.Get the frame size from the user
3.To create the frame based on the user request.
4.To send frames to server from the client side.
5.If your frames reach the server it will send ACK signal to client otherwise it will
send NACK signal to client.
6.Stop the program
PROGRAM :
import javax.swing.*;
import java.net.*;
import java.awt.image.*;
import javax.imageio.*;
import java.io.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class Client{
public static void main(String args[]) throws Exception{
Socket soc;
BufferedImage img = null;
soc=new Socket("localhost",4000);
System.out.println("Client is running. ");
try {
System.out.println("Reading image from disk. ");
img = ImageIO.read(new File("dig.jpg"));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(img, "jpg", baos);
baos.flush();
byte[] bytes = baos.toByteArray();
baos.close();
System.out.println("Sending image to server. ");
OutputStream out = soc.getOutputStream();
DataOutputStream dos = new DataOutputStream(out);
dos.writeInt(bytes.length);
dos.write(bytes, 0, bytes.length);
System.out.println("Image sent to server. ");
dos.close();
out.close();
}catch (Exception e) {
System.out.println("Exception: " + e.getMessage());
soc.close();
soc.close();
}
}
}
\\server.java
import java.net.*;
import java.io.*;
import java.awt.image.*;
import javax.imageio.*;
import javax.swing.*;
class Server {
public static void main(String args[]) throws Exception{
ServerSocket server=null;
Socket socket;
server=new ServerSocket(4000);
System.out.println("Server Waiting for image");
socket=server.accept();
System.out.println("Client connected.");
InputStream in = socket.getInputStream();
DataInputStream dis = new DataInputStream(in);
int len = dis.readInt();
System.out.println("Image Size: " + len/1024 + "KB");
byte[] data = new byte[len];
dis.readFully(data);
dis.close();
in.close();
InputStream ian = new ByteArrayInputStream(data);
BufferedImage bImage = ImageIO.read(ian);
JFrame f = new JFrame("Server");
ImageIcon icon = new ImageIcon(bImage);
JLabel l = new JLabel();
l.setIcon(icon);
f.add(l);
f.pack();
f.setVisible(true);
OUTPUT:
RESULT :
Thus the program was implementing to socket for HTTP for web page upload and
download.
EX-NO 6.
DATE:
AIM:
#include<stdio.h>
#include "simp.h"
int add(CLIENT *clnt,int x,int y)
operands ops;
int *result;
ops.x=x;
ops.y=y;
result=add_1(&ops,clnt);
if(result==NULL)
{
fprintf(stderr,"Trouble calling remote procedure\n");
exit(0);
}
return(*result);
int sub(CLIENT *clnt,int x,int y)
operands ops;
int *result;
ops.x=x;
ops.y=y;
result=sub_1(&ops,clnt);
if(result==NULL)
{
fprintf(stderr,"Trouble calling remote procedure\n");
exit(0);
}
return(*result);
int main(int argc,char *argv[])
CLIENT *clnt;
int x,y;
if(argc!=4)
{
fprintf(stderr,"Usage:%s hostname num1 num\n",argv[0]);
exit(0);
}
clnt=clnt_create(argv[1],SIMP_PROG,SIMP_VERSION,"udp");
if(clnt==(CLIENT *)NULL)
{
clnt_pcreateerror(argv[1]);
exit(1);
}
x=atoi(argv[2]);
y=atoi(argv[3]);
printf("%d + %d=%d\n",x,y,add(clnt,x,y));
printf("%d - %d=%d\n",x,y,sub(clnt,x,y));
return(0);
//OUTPUT:
//GENERATION OF STUBS AND HEADER FILE
rmk@rmk-desktop:~/NWLAB/RPC$rpcgen -C -a simp.x
//Make sure that the following files are generated by rpcgen tool
rmk@rmk-desktop:~/NWLAB/RPC$ ls
a.out
simpclient.c simp_server.c simp.x
Makefile.simp simp_clnt.c simpservice.c simp_xdr.c
simp_client.c simp.h
simp_svc.c
//SERVER
rmk@rmk-desktop:~/NWLAB/RPC$ cc simpservice.c simp_svc.c simp_xdr.c
rmk@rmk-desktop:~/NWLAB/RPC$ ./a.out
Got request: adding 6, 3
Got request: subtracting 6, 3
//CLIENT
rmk@rmk-desktop:~/NWLAB/RPC$ cc simpclient.c simp_clnt.c simp_xdr.c
rmk@rmk-desktop:~/NWLAB/RPC$ ./a.out 127.0.0.1 6 3
6+3=9
6-3=3
rmk@rmk-desktop:~/NWLAB/RPC$
Result:
Thus the java program to implement RPC (remote procedure call ) is implemented.
EX NO:7
Date:
IMPLEMENTATION OF SUBNETTING
AIM:
Write a program to implement subnetting and find the subnet masks.
PROGRAM:
import
class Subnet{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.print(Enter the ip address: );
String ip = sc.nextLine();
String split_ip[] = ip.split(\\.); //SPlit the string after every .
String split_bip[] = new String[4]; //split binary ip
String bip = ;
for(int i=0;i<4;i++){
split_bip[i] = appendZeros(Integer.toBinaryString(Integer.parseInt(split_ip[i]))); //
18 => 18 => 10010 => 00010010
bip += split_bip[i];
}
System.out.println(IP in binary is +bip);
System.out.print(Enter the number of addresses: );
int n = sc.nextInt();
//Calculation of mask
int bits = (int)Math.ceil(Math.log(n)/Math.log(2)); /*eg if address = 120, log
120/log 2 gives log to the base 2 => 6.9068, ceil gives us upper integer */
System.out.println(Number of bits required for address = +bits);
int mask = 32-bits;
System.out.println(The subnet mask is = +mask);
//Calculation of first address and last address
int fbip[] = new int[32];
for(int i=0; i<32;i++) fbip[i] = (int)bip.charAt(i)-48; //convert cahracter 0,1 to integer
0,1
for(int i=31;i>31-bits;i)//Get first address by ANDing last n bits with 0
fbip[i] &= 0;
String fip[] = {,,,};
for(int i=0;i<32;i++)
fip[i/8] = new String(fip[i/8]+fbip[i]);
System.out.print(First address is = );
for(int i=0;i<4;i++){
System.out.print(Integer.parseInt(fip[i],2));
if(i!=3) System.out.print(.);
}
System.out.println();
int lbip[] = new int[32];
for(int i=0; i<32;i++) lbip[i] = (int)bip.charAt(i)-48; //convert cahracter 0,1 to integer
0,1
for(int i=31;i>31-bits;i)//Get last address by ORing last n bits with 1
lbip[i] |= 1;
String lip[] = {,,,};
for(int i=0;i<32;i++)
lip[i/8] = new String(lip[i/8]+lbip[i]);
System.out.print(Last address is = );
for(int i=0;i<4;i++){
System.out.print(Integer.parseInt(lip[i],2));
if(i!=3) System.out.print(.);
}
System.out.println();
}
static String appendZeros(String s){
String temp = new String(00000000);
return temp.substring(s.length())+ s;
}
}
/*Output
Enter the ip address: 100.110.150.10
IP in binary is 01100100011011101001011000001010
Enter the number of addresses: 7
Number of bits required for address = 3
The subnet mask is = 29
First address is = 100.110.150.8
Last address is = 100.110.150.15
*/
Result :
Thus the Program was displayed implement subnetting and find the subnet
masks.
EX NO: 8
AIM :
To write a C program for application using TCP Sockets Links .
ALGORITHM :
1.Start the program.
2.Get the frame size from the user
3.To create the frame based on the user request.
4.To send frames to server from the client side.
5.If your frames reach the server it will send ACK signal to client otherwise it will
send NACK signal to client.
6.Stop the program
a) TCP ECHO CLIENT SERVER - ITERATIVE MODEL:
//iterserv.c -- Iterative Echo Server
#include<stdio.h>
#include<time.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<sys/socket.h>
#include<string.h>
#include<unistd.h>
#define PORT 7783
void str_echo(int sockfd);
int main(int argc, char *argv[])
{
char buffer[30];
int sockfd,connfd,a,len;
time_t sec;
struct sockaddr_in servaddr,cliaddr;
printf("ECHO SERVER .....\n\n");
sockfd=socket(AF_INET,SOCK_STREAM,0);
if(sockfd==-1)
printf("ERROR CREATING SOCKET!");
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family=AF_INET;
servaddr.sin_port=htons(PORT);
servaddr.sin_addr.s_addr=htonl(INADDR_ANY);
bind(sockfd,(struct sockaddr *)&servaddr,sizeof(servaddr));
if((a=listen(sockfd,5))<0)
printf("ERROR IN LISTEN FUNCTION!");
printf("ECHO SERVER STARTED");
while(1)
{
len=sizeof(cliaddr);
connfd=accept(sockfd,(struct sockaddr*)&cliaddr,&len);
str_echo(connfd);
close(sockfd);
}
printf("ECHO SERVER CLOSING");
}
void str_echo(int sfd)
{
int num;
char buff[30];
printf("\nECHO FUNCTION...\n");
for(;;)
{
if((num=read(sfd,buff,sizeof(buff)))==0)
write(sfd,buff,num);
}
}
//itercli.c -- Echo client
#include<stdio.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<string.h>
#include<unistd.h>
#define PORT 7783
void str_cli(FILE *fp,int sfd);
return;
int main(int argc,char *argv[])
{
int sockfd;
struct sockaddr_in serv;
char buff[30];
printf("ECHO CLIENT...\nid---");
sockfd=socket(AF_INET,SOCK_STREAM,0);
printf("%d",sockfd);
if (sockfd ==0)
printf("Socket Creation Error");
printf("Socket created");
memset(&serv,0,sizeof(serv));
serv.sin_family=AF_INET;
serv.sin_port=htons(PORT);
serv.sin_addr.s_addr=inet_addr(argv[1]);
pid_t pid;
struct sockaddr_in servaddr,cliaddr;
sockfd=socket(AF_INET,SOCK_STREAM,0);
if(sockfd==-1)
{
printf("Error creating socket\n");
exit(0);
}
printf("Server Socket Created Successfully.\n");
bzero((struct sockaddr *)&servaddr,sizeof(servaddr));
servaddr.sin_family=AF_INET;
servaddr.sin_port=htons(PORT);
servaddr.sin_addr.s_addr=htonl(INADDR_ANY);
if(bind(sockfd,(struct sockaddr *)&servaddr,sizeof(servaddr))<0)
{
printf("Error in BIND function");
exit(0);
}
printf("Server Socket Binded.\n");
if((a=listen(sockfd,5))==-1)
{
printf("Error in LISTEN function");
exit(0);
}
printf("Server Socket Listened...\n");
len=sizeof(cliaddr);
if((connfd=accept(sockfd,(struct sockaddr *)&cliaddr,&len))<0)
{
printf("Error in ACCEPT");
exit(0);
}
do
{
strcpy(buffer," ");
read(connfd,buffer,100);
printf("From client :%s",buffer);
if(strcmp(buffer,"bye\n")==0)
{
printf("from Client: %s",buffer);
goto stop;
}
printf("Server :");
fgets(buffer,sizeof(buffer),stdin);
write(connfd,buffer,100);
}while(strcmp(buffer,"bye\n")!=0);
stop:
exit(0);
close(connfd);
return 0;
}
//tcpchatcli.c -- TCP CHAT CLIENT
#include<stdio.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<string.h>
#include<unistd.h>
#include<stdlib.h>
#define PORT 4771
int main(int argc,char *argv[])
{
int sockfd;
struct sockaddr_in serv;
char buff[100];
sockfd=socket(AF_INET,SOCK_STREAM,0);
printf("Client Socket Created Successfully.\n");
memset(&serv,0,sizeof(serv));
serv.sin_family=AF_INET;
serv.sin_port=htons(PORT);
serv.sin_addr.s_addr=inet_addr(argv[1]);
if (connect(sockfd,(struct sockaddr *)&serv, sizeof(serv))<0)
{
printf("error in connect");
exit(0);
}
printf("Client Socket with Server Successfully.\n");
do
{
strcpy(buff," ");
printf("Client. :");
fgets(buff,100,stdin);
write(sockfd,buff,100);
if(strcmp(buff,"bye\n")==0)
{
printf("Client: %s",buff);
goto stop;
}
strcpy(buff," ");
read(sockfd,buff,sizeof(buff));
Result:
Thus the a C program for application using TCP Sockets Links are implemented.
C.FILE TRANSFER
AIM:
To write a java program for applaction using TCP Sockets.
PROGRAM:FILE CLIENT
import java.io.*;
import java.net.*;
importjava.util.*;
classClientfile
{
public static void main(String args[])
{
Try
{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
Socket clsct=new Socket("127.0.0.1",139);
DataInputStream din=new DataInputStream(clsct.getInputStream());
DataOutputStreamdout=new DataOutputStream(clsct.getOutputStream());
System.out.println("Enter the file name:");
String str=in.readLine();
dout.writeBytes(str+'\n');
System.out.println("Enter the new file name:");
String str2=in.readLine();
String str1,ss;
FileWriter f=new FileWriter(str2);
char buffer[];
while(true)
{ str1=din.readLine();
if(str1.equals("-1")) break;
System.out.println(str1);
buffer=new char[str1.length()];
str1.getChars(0,str1.length(),buffer,0);
f.write(buffer);
}
f.close();
clsct.close();
}
catch (Exception e)
{System.out.println(e);} }}
SERVER:
import java.io.*;
import java.net.*;
importjava.util.*;
classServerfile
{ public static void main(String args[]){
Try
{ ServerSocketobj=new ServerSocket(139);
while(true)
{ Socket obj1=obj.accept();
DataInputStream din=new DataInputStream(obj1.getInputStream());
DataOutputStreamdout=new DataOutputStream(obj1.getOutputStream());
String str=din.readLine();
FileReader f=new FileReader(str);
BufferedReader b=new BufferedReader(f);
String s;
while((s=b.readLine())!=null)
{ System.out.println(s);
dout.writeBytes(s+'\n'); }
f.close();
dout.writeBytes("-1\n"); } }
catch(Exception e)
{ System.out.println(e);}}}
OUTPUT:
File content
Computer networks
jhfcgsauf
jbsdava
jbvuesagv
client
Enter the file name: sample.txt
server
Computer networks
jhfcgsauf
jbsdava
jbvuesagv
client
Enter the new file name:
net.txt
Computer networks
jhfcgsauf
jbsdav
jbvuesagv
Destination file
Computer networks
jhfcgsauf
jbsdava
jbvuesagv
RESULT:
Thus the program was displayed for application using file transfer
EX NO 9 :
DATE:
servaddr.sin_port=htons(PORT);
servaddr.sin_addr.s_addr=htonl(INADDR_ANY);
bind(listenfd,(SA *)&servaddr,sizeof(servaddr));
listen(listenfd,10);
for(;;)
{
len=sizeof(cliaddr);
connfd=accept(listenfd,(SA *)&cliaddr,&len);
read(connfd,host,sizeof(host));
printf("%s\n",host);
if((hp=gethostbyname(host))==NULL)
inet_ntop(AF_INET,hp->h_addr,buff,sizeof(buff));
printf("\nHOST : %s --> IP ADDRESS --> %s",host,buff);
printf("\n1");
write(connfd,buff,sizeof(buff));
close(connfd);
}
printf("Cannot get address\n");
return 0;
}
//DNSClient.c
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<netdb.h>
#define SA struct sockaddr
#define PORT 7882
int main(int argc,char **argv)
{
socklen_t len;
struct sockaddr_in servaddr;
char buff[200],host[100];
int sockfd;
sockfd=socket(AF_INET,SOCK_STREAM,0);
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family=AF_INET;
servaddr.sin_port=htons(PORT);
servaddr.sin_addr.s_addr=inet_addr("127.0.0.1");
if(connect(sockfd,(SA *)&servaddr,sizeof(servaddr))<0)
printf("Connect error");
printf("Enter the domain name");
scanf("%s",host);
write(sockfd,host,sizeof(host));
if(read(sockfd,buff,sizeof(buff))<0)
printf("Read error");
printf("\nThe host address is %s\n",buff);
return 0;
}
OUTPUT:
//SERVER
rmk@rmk-desktop:~/NWLAB/DNS$ cc DNSServer.c
rmk@rmk-desktop:~/NWLAB/DNS$ ./a.out
DNS SERVER...
DNS Server Started
www.google.com
HOST : www.google.com --> IP ADDRESS --> 74.125.71.104
1www.rmkec.ac.in
HOST : www.rmkec.ac.in --> IP ADDRESS --> 173.193.3.233
//CLIENT
rmk@rmk-desktop:~/NWLAB/DNS$ cc DNSClient.c
rmk@rmk-desktop:~/NWLAB/DNS$ ./a.out 127.0.0.1
Enter the domain namewww.google.com
The host address is 74.125.71.104
rmk@rmk-desktop:~/NWLAB/DNS$ ./a.out 127.0.0.1
Enter the domain namewww.rmkec.ac.in
The host address is 173.193.3.233
rmk@rmk-desktop:~/NWLAB/DNS$
RESULT:
Thus the output for the application using TCP is implemented and output is verified.
b.SNMP
AIM :
To write a java program for SNMP application program
ALGORITHM :
1.Start the program.
2.Get the frame size from the user
3.To create the frame based on the user request.
4.To send frames to server from the client side.
5.If your frames reach the server it will send ACK signal to client otherwise it will
send NACK signal to client.
6.Stop the program.
PROGRAM:
importjava.io.IOException;
import org.snmp4j.CommunityTarget;
import org.snmp4j.PDU;
import org.snmp4j.Snmp;
import org.snmp4j.Target;
import org.snmp4j.TransportMapping;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.smi.Address;
import org.snmp4j.smi.GenericAddress;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.OctetString;
import org.snmp4j.smi.VariableBinding;
import org.snmp4j.transport.DefaultUdpTransportMapping;
public class SNMPManager {
Snmpsnmp = null;
String address = null;
* Constructor
* @param
add
*/
publicSNMPManager(String add)
{
address = add;
public static void main(String[] args) throws IOException {
/**
* Port 161 is used for Read and Other operations
* Port 162 is used for the trap generation
*/
SNMPManager client = new SNMPManager("udp:127.0.0.1/161");
client.start();
/**
* OID - .1.3.6.1.2.1.1.1.0 =>SysDec
* OID - .1.3.6.1.2.1.1.5.0 =>SysName
* => MIB explorer will be usefull here, as discussed in previous article
*/
String sysDescr = client.getAsString(new OID(".1.3.6.1.2.1.1.1.0"));
System.out.println(sysDescr);
}
/**
* get any answers because the communication is asynchronous
OUT PUT :
Hardware: x86 Family 6 Model 23 Stepping 10 AT/AT COMPATIBLE Software: Windows
2000 Version 5.1 (Build 2600 Multiprocessor Free)
RESULT:
Thus the SNMP program was displayedand the output is verified.
C.File Transfer
AIM:
To write a java program for applaction using TCP and UDP Sockets Liks
Program:File Client
import java.io.*;
import java.net.*;
importjava.util.*;
classClientfile
{ public static void main(String args[])
{
Try
{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
Socket clsct=new Socket("127.0.0.1",139);
DataInputStream din=new DataInputStream(clsct.getInputStream());
DataOutputStreamdout=new DataOutputStream(clsct.getOutputStream());
System.out.println("Enter the file name:");
String str=in.readLine();
dout.writeBytes(str+'\n');
System.out.println("Enter the new file name:");
String str2=in.readLine();
String str1,ss;
FileWriter f=new FileWriter(str2);
char buffer[];
while(true)
{ str1=din.readLine();
if(str1.equals("-1")) break;
System.out.println(str1);
buffer=new char[str1.length()];
str1.getChars(0,str1.length(),buffer,0);
f.write(buffer);
}
f.close();
clsct.close();
}
catch (Exception e)
{
System.out.println(e);
}
}
}
Server:
import java.io.*;
import java.net.*;
importjava.util.*;
classServerfile
{ public static void main(String args[]){
Try
{
ServerSocketobj=new ServerSocket(139);
while(true)
{
Socket obj1=obj.accept();
DataInputStream din=new DataInputStream(obj1.getInputStream());
DataOutputStreamdout=new DataOutputStream(obj1.getOutputStream());
String str=din.readLine();
FileReader f=new FileReader(str);
BufferedReader b=new BufferedReader(f);
String s;
while((s=b.readLine())!=null)
{ System.out.println(s);
dout.writeBytes(s+'\n');
}
f.close();
dout.writeBytes("-1\n");
}}
catch(Exception e)
{ System.out.println(e);}
}}
OUTPUT:
File content
Computer networks
jhfcgsauf
jbsdava
jbvuesagv
client
Enter the file name:
sample.txt
server
Computer networks
jhfcgsauf
jbsdava
jbvuesagv
client
Enter the new file name:
net.txt
Computer networks
jhfcgsauf
jbsdava
jbvuesagv
Destination file
Computer networks
jhfcgsauf
jbsdava
jbvuesagv
RESULT:
Thus the program was displayed for application using file transfer
EX NO:10
Date:
INTRODUCTION:
NS is a discrete event simulator for networking research. It provides substantial
support for simulation of TCP, routing, and multicast protocols over wired and wireless
(local and satellite) networks.
ns is an object oriented simulator, written in C++, with an OTcl interpreter as a
frontend. The simulator supports a class hierarchy in C++ (also called the compiled
hierarchy in this document), and a similar class hierarchy within the OTcl interpreter
(also called the interpreted hierarchy in this document). The two hierarchies are closely
related to each other; from the users perspective, there is a one-to-one correspondence
between a class in the interpreted hierarchy and one in the compiled hierarchy.
ns uses two languages because simulator has two different kinds of things it needs
to do. On one hand, detailed simulations of protocols require a systems programming
language which can efficiently manipulate bytes, packet headers, and implement
algorithms that run over large data sets. For these tasks run-time speed is important and
turn-around time (run simulation, find bug, fix bug, recompile, re-run) is less important.
On the other hand, a large part of network research involves slightly varying parameters
or configurations, or quickly exploring a number of scenarios. In these cases, iteration
time (change the model and re-run) is more important. Since onfiguration runs once (at
the beginning of the simulation), run-time of this part of the task is less important. ns
meets both of these needs with two languages, C++ and OTcl. C++ is fast to run but
slower to change, making it suitable for detailed protocol implementation. OTcl runs
much slower but can be changed very quickly (and interactively), making it ideal for
simulation configuration. ns (via tclcl) provides glue to make objects and variables
appear on both langauges.
Nam is a Tcl/TK based animation tool for viewing network simulation traces and
real world packet traces. It supports topology layout, packet level animation, and various
data inspection tools.Nam began at LBL. It has evolved substantially over the past few
years. The nam development effort was an ongoing collaboration with the VINT project.
How to start:
First of all, you need to create a simulator object. This is done with the command
Now we open a file for writing that is going to be used for the nam trace data.
set nf [open out.nam w]
$ns namtrace-all $nf
The first line opens the file 'out.nam' for writing and gives it the file handle 'nf'. In
thesecond line we tell the simulator object that we created above to write all simulation
data that is going to be relevant for nam into this file.The next step is to add a 'finish'
procedure that closes the trace file and starts nam.
proc finish {} {
global ns nf
$ns flush-trace
close $nf
exec nam out.nam &
exit 0}
The next line tells the simulator object to execute the 'finish' procedure after 5.0
seconds of simulation time.
$ns at 5.0 "finish"
ns provides you with a very simple way to schedule events with the 'at' command. The
last line finally starts the simulation.
$ns run
You can actually save the file now and try to run it with 'ns example1.tcl'. You are going
to get an error message like 'nam: empty trace file out.nam' though, because until now we
haven't defined any objects (nodes, links, etc.) or events. You will have to use the code
from this section as starting point in the other sections. #Create a simulator object
set ns [new Simulator]
#Open the nam trace file
set nf [open out.nam w]
$ns namtrace-all $nf
#Define a 'finish' procedure
proc finish {} {
global ns nf
$ns flush-trace
#Close the trace file
close $nf
#Execute nam on the trace file
exec nam out.nam &
exit 0
}
# Insert your own code for topology creation
# and agent definitions, etc. here
#Call the finish procedure after 5 seconds simulation time
sends data from node n0, and another agent object that receives the data on node n1.
#Create a UDP agent and attach it to node n0
set udp0 [new Agent/UDP]
$ns attach-agent $n0 $udp0
# Create a CBR traffic source and attach it to udp0
set cbr0 [new Application/Traffic/CBR]
$cbr0 set packetSize_ 500
$cbr0 set interval_ 0.005
$cbr0 attach-agent $udp0
These lines create a UDP agent and attach it to the node n0, then attach a CBR
traffic generator to the UDP agent. CBR stands for 'constant bit rate'. Line 7 and 8 should
be self-explaining. The packet Size is being set to 500 bytes and a packet will be sent
every 0.005 seconds (i.e. 200 packets per second).
The next lines create a Null agent which acts as traffic sink and attach it to node n1.
set null0 [new Agent/Null]
$ns attach-agent $n1 $null0
Now the two agents have to be connected with each other.
$ns connect $udp0 $null0
And now we have to tell the CBR agent when to send data and when to stop sending.
Note: It's probably best to put the following lines just before the line '$ns at 5.0 "finish"'.
$ns at 0.5 "$cbr0 start"
$ns at 4.5 "$cbr0 stop"
This code should be self-explaining again. Now you can save the file and start the
simulation again. When you click on the 'play' button in the nam window, you will see
that after 0.5 simulation seconds,node 0 starts sending data packets to node 1. You might
want to slow nam down then with the 'Step' slider.
Now you start some experiments with nam and the Tcl script. You can click on any
packet in the nam window to monitor it, and you can also click directly on the link to get
some graphs with statistics.Try to change the 'packetsize_' and 'interval_' parameters in
the Tcl script to see what happens.
Agents:
EX NO:11
DATE:
has become the dominant form of addressing on the Internet. Bridging is still widely
used within localized environments.
LINK STATE ROUTING ALGORITHM:
#routing2.tcl
set ns [new Simulator]
#Define different colors for data flows (for NAM)
$ns color 1 Blue
$ns color 2 Red
#Open the Trace file
set file1 [open routing2.tr w]
$ns trace-all $file1
#Open the NAM trace file
set file2 [open routing2.nam w]
$ns namtrace-all $file2
#Define a 'finish' procedure
proc finish {} {
global ns file1 file2
$ns flush-trace
close $file1
close $file2
exec nam routing2.nam &
exit 0
}
$ns rtproto LS
#Create six nodes
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
set n4 [$ns node]
set n5 [$ns node]
#Create links between the nodes
$ns duplex-link $n0 $n1 0.3Mb 10ms DropTail
$ns duplex-link $n1 $n2 0.3Mb 10ms DropTail
$ns duplex-link $n2 $n3 0.3Mb 10ms DropTail
$ns duplex-link $n1 $n4 0.3Mb 10ms DropTail
$ns duplex-link $n3 $n5 0.5Mb 10ms DropTail
$ns duplex-link $n4 $n5 0.5Mb 10ms DropTail
#Give node position (for NAM)
$ns duplex-link-op $n0 $n1 orient right
$ns duplex-link-op $n1 $n2 orient right
$ns duplex-link-op $n2 $n3 orient up-down
$ns duplex-link-op $n1 $n4 orient up-left
direction. In selective flooding the routers don't send every incoming packet on every
line but only on those lines which are going approximately in the right direction.
Advantages :
f a packet can be delivered, it will (probably multiple times).
Since flooding naturally utilizes every path through the network, it will also use the
shortest path.
This algorithm is very simple to implement.
Disadvantages :
Flooding can be costly in terms of wasted bandwidth. While a message may only
have one destination it has to be sent to every host. In the case of a ping flood or a
denial of service attack, it can be harmful to the reliability of a computer network.
Messages can become duplicated in the network further increasing the load on the
networks bandwidth as well as requiring an increase in processing complexity to
disregard duplicate messages.
Duplicate packets may circulate forever, unless certain precautions are taken:
Use a hop count or a time to live count and include it with each packet. This value
should take into account the number of nodes that a packet may have to pass through
on the way to its destination.
Have each node keep track of every packet seen and only forward each packet once
Enforce a network topology without loops
III . DISTANCE VECTOR
In computer communication theory relating to packet-switched networks, a distancevector routing protocol is one of the two major classes of routing protocols, the other
major class being the link-state protocol. Distance-vector routing protocols use the
BellmanFord algorithm, FordFulkerson algorithm, or DUAL FSM (in the case of Cisco
Systems's protocols) to calculate paths.
A distance-vector routing protocol requires that a router informs its neighbors of
topology changes periodically. Compared to link-state protocols, which require a router
to inform all the nodes in a network of topology changes, distance-vector routing
protocols have less computational complexity and message overhead.
The term distance vector refers to the fact that the protocol manipulates vectors (arrays)
of distances to other nodes in the network. The vector distance algorithm was the
original ARPANET routing algorithm and was also used in the internet under the name
of RIP (Routing Information Protocol).
Examples of distance-vector routing protocols include RIPv1 and RIPv2 and IGRP.
Method :
Routers using distance-vector protocol do not have knowledge of the entire path to a
destination. Instead they use two methods:
1. Direction in which router or exit interface a packet should be forwarded.
RESULT :
Thus The Perform a case study about the different routing algorithms to select
the network path with itsoptimum and economical during data transfer. Was
complicated .