Ra1911042010003 CN Lab

Download as pdf or txt
Download as pdf or txt
You are on page 1of 59

INDEX

EXP TITLE PAGE DATE SIGN


NO No

1 2
BASIC NETWORKING COMMANDS

2 CLIENT SERVER COMMUNICATION (SOCKET 7


PROGRAMMING)

3 CODE FOR SIMULATING PING AND TRACEROUTE 10


COMMANDS

4 CREATE SOCKET FOR HTTP, TO WEBPAGE UPLOAD AND 12


DOWNLOAD

5 15
SIMULATION OF ERROR CORRECTION CODE (CRC)

6 17
IMPLEMENTATION OF STOP AND WAIT PROTOCOL

7 21
SIMULATION OF SLIDING WINDOW PROTOCOL

8 26
SIMULATING ARP PROTOCOLS

9 PROGRAM FOR REVERSE ADDRESS RESOLUTION 29


PROTOCOL USING UDP

10 ECHO CLIENT AND ECHO SERVER 33

11 37
CHAT

12 40
FILE TRANSFER

13 43
SIMULATION OF DNS USING UDP SOCKETS
Date: BASIC NETWORKING COMMANDS
Expt.No: 01

AIM: To implement basic networking keywords

Algorithm:
1. Study the basic networking commands.
2. Run the networking commands along with their arguments and parameters.
3. Observe the output on the command line.
4. Record observations in the journal.

SOURCE CODE:

1. Ipconfig
Description: (Internet Protocol CONFIGuration) A command line utility
that is used to display and manage the IP address assigned to the machine.
Syntax: ipconfig
Eg: ipconfig

2.Ping
Description: The ping command is a Command Prompt command used to
test the ability of the source computer to reach a specified destination
computer.
Syntax: ping <IP address>, ping < Domain Name>
Eg: ping www.google.com

3.Hostname
Description: It is used to obtain the DNS(Domain Name System) name and
set the system's hostname or NIS(Network Information System) domain
name. A hostname is a name which is given to a computer and it attached
to the network. Its main purpose is to uniquely identify over a network.
Syntax: hostname
Eg: hostname

4.Getmac
Description: Getmac is a Windows command used to display the Media
Access Control (MAC) addresses for each network adapter in the
computer.
Syntax: getmac
Eg: getmac
5.NetStat
Description: The netstat provides the statistics and information in the use
of the current TCP-IP Connection network about the protocol.
Syntax: netstat [-a] [-b] [-e] [-n] [-o] [-p <Protocol>] [-r] [-s] [<interval>]
Eg: Netstat -n

6.Tracert
Description: The tracert command is a Command Prompt command which
is used to get the network packet being sent and received and the number
of hops required for that packet to reach to target.
Syntax: tracert [-d] [-h MaxHops] [-w TimeOut] target
Eg: tracert www.google.com

7. Nslookup
Description: The Nslookup, which stands for name server lookup
command, is a network utility command used to obtain information about
internet servers. It provides name server information for the DNS (Domain
Name System), i.e. the default DNS server’s name and IP Address.
Syntax: Nslookup , Nslookup < domain name>
Eg: Nslookup www.youtube.com

8.Arp
Description: The ARP command provides information like Address, Flags,
Mask, IFace, Hardware Type, Hardware Address, etc.
Syntax: arp [/a [<inetaddr>] [/n <ifaceaddr>]] [/g [<inetaddr>] [-n
<ifaceaddr>]] [/d <inetaddr> [<ifaceaddr>]] [/s <inetaddr> <etheraddr>
[<ifaceaddr>]]
Eg: arp -a

9. Nbtstat
Description: Nbtstat is designed to help troubleshoot NetBIOS name
resolution problems.
Syntax: nbtstat < -a (name)> < -A (IP-address)> < -c>< -n> <-r> <-R><-RR>
<-S> <-s>
Eg: nbtstat -c

10.Path Ping
Description: The pathping command which provides a combination of the
best aspects of Tracert and Ping.
Syntax: pathping [/n] [/h <maximumhops>] [/g <hostlist>] [/p <Period>]
[/q <numqueries> [/w <timeout>] [/i <IPaddress>] [/4 <IPv4>] [/6
<IPv6>][<targetname>]
Eg: pathping 8.8.8.8
OUTPUT:
RESULT: Basic Networking Commands are implemented successfully.
Date:- CLIENT SERVER COMMUNICATION (SOCKET
Expt.No:- 02 PROGRAMMING)

AIM: To Implement Client-Server Communication


Algorithm:
CLIENT SIDE
STEP 1: Start the program. CLIENT
STEP 2: Declare the variables and structure.
STEP 3: A socket is created and connect function is executed.
STEP 4: If the connection is successful then the server sends the message.
STEP 5: The date and time are printed on the client-side.
STEP 6: Stop the program.
SERVER SIDE
STEP 1: Start the program. SERVER
STEP 2: Declare the variables and structure for the socket.
STEP 3: The socket is bound at the specified port.
STEP 4: Using the object the port and address are declared.
STEP 5: The listen and accept functions are executed.
STEP 6: If the binding is successful it waits for the client's request.
STEP 7: Execute the client program.

SOURCE CODE:
Server

#include <sys/socket.h>

#include <ne net/in.h>

#include <arpa/inet.h>

#include <stdio.h>

#include <stdlib.h>

#include <unistd.h>
#include <errno.h>

#include <string.h>

#include <sys/types.h>

#include < me.h>


int main(int argc, char *argv[])

int listenfd = 0, connfd = 0;

struct sockaddr_in serv_addr;

char sendBuff[1025];

me_t cks;

listenfd = socket(AF_INET, SOCK_STREAM, 0);

memset(&serv_addr, '0', sizeof(serv_addr));

memset(sendBuff, '0', sizeof(sendBuff));

serv_addr.sin_family = AF_INET;

serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);

serv_addr.sin_port = htons(5000);

bind(listenfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr));

listen(listenfd, 10);

while(1)

connfd = accept(listenfd, (struct sockaddr*)NULL, NULL);

cks = me(NULL);

snprin (sendBuff, sizeof(sendBuff), "%.24s\r\n", c me(& cks));

write(connfd, sendBuff, strlen(sendBuff));

close(connfd);

sleep(1);

}
Client

#include <sys/socket.h>

#include <sys/types.h>

#include <ne net/in.h>

#include <netdb.h>

#include <stdio.h>

#include <string.h>

#include <stdlib.h>

#include <unistd.h>

#include <errno.h>

#include <arpa/inet.h>

int main(int argc, char *argv[])

int sockfd = 0, n = 0;

char recvBuff[1024];

struct sockaddr_in serv_addr;

if(argc != 2)

prin ("\n Usage: %s <ip of server> \n",argv[0]);

return 1;

memset(recvBuff, '0',sizeof(recvBuff));

if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)

prin ("\n Error : Could not create socket \n");

return 1;

memset(&serv_addr, '0', sizeof(serv_addr));

serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(5000);

if(inet_pton(AF_INET, argv[1], &serv_addr.sin_addr)<=0)

prin ("\n inet_pton error occured\n");

return 1;

if( connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)

prin ("\n Error : Connect Failed \n");

return 1;

while ( (n = read(sockfd, recvBuff, sizeof(recvBuff)-1)) > 0)

recvBuff[n] = 0;

if(fputs(recvBuff, stdout) == EOF)

prin ("\n Error : Fputs error\n");

if(n < 0)

prin ("\n Read error \n");

return 0;

}
OUTPUT:

RESULT: Client Server Communication using socket programming has been implemented
successfully.
Date CODE FOR SIMULATING PING AND TRACEROUTE
Expt.No:- 03 COMMANDS

AIM: To Write The java program for simulating ping and traceroute commands

ALGORITHM:
PING :
Step 1: Start the program.
Step 2: Import net and packages.
Step 3: Get the ip address
Step 4: Ping the remote server using Ping Command
Step 5: The Packet statistics of the pinged server is displayed

TRACEROUTE:
Step 1: Start the program.
Step 2: Import net and packages.
Step 3: Get the ip address
Step 4: Traceroute the remote server using traceroute Command
Step 5: The number of max hopes and byte packets is displayed.

SOURCE CODE:
Ping
import java.net.*;
import java.io.*;
import java.util.*;
public class pingTest {
public static void main(String[] args) {
String ipa = args[0];
String pingResult = "";
String pingCmd = "ping " + ipa;
try {
Runtime r = Runtime.getRuntime();
Process p = r.exec(pingCmd);
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
pingResult += inputLine;
}
in.close();
}//try
catch (IOException e) {
System.out.println(e);
}
}
}
Traceroute
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class traceroute
{
public static void runSystemCommand(String command)
{
try
{
Process p = Runtime.getRuntime().exec(command);
BufferedReader inputStream = new BufferedReader(
new InputStreamReader(p.getInputStream()));
String s = "";
while ((s = inputStream.readLine()) != null)
System.out.println(s);
}
catch (Exception e)
{
}
}
public static void main(String[] args)
{
String ip = "www.google.co.in";

runSystemCommand("traceroute " + ip);


}
}

OUTPUT
RESULT: Thus the program was implemented to simulate ping and traceroute commands.
Date CREATE SOCKET FOR HTTP, TO WEBPAGE UPLOAD AND
Expt.No:- 04 DOWNLOAD

AIM: To write a java program for socket for HTTP for web page upload and download .

ALGORITHM:

Step 1: Start the program.


Step 2: Get the frame size from the user
Step 3: To create the frame based on the user request.
Step 4: To send frames to server from the client side.
Step 5: If your frames reach the server it will send ACK signal to client otherwise it will send NACK
signal to client.
Step 6: Stop the program

SOURCE CODE:
Server
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);
}}

Client
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("dog.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();
}
}
OUTPUT

RESULT: Thus the program was implementing to socket for HTTP for web page upload and download.
Date SIMULATION OF ERROR CORRECTION CODE (CRC)
Expt.No:- 05

AIM: To Simulation of Error Correction Code .

ALGORITHM

CRC:
Step 1: Open the editor and type the program for error detection
Step 2: Get the input in the form of bits.
Step 3: Append the redundancy bits.
Step 4: Divide the appended data using a divisor polynomial.
Step 5: The resulting data should be transmitted to the receiver.
Step 6: At the receiver the received data is entered.
Step 7: The same process is repeated at the receiver.
Step 8: If the remainder is zero there is no error otherwise there is some error in the received bits
Step 9: Run the program.

HAMMING CODE
Step 1: Start the program.
Step 2: Import net and packages.
Step 3: Get the 7-bit data code
Step 4: Calculation of the number of redundant bits.
Step 5: Position the redundant bits.
Step 6: Calculate the values of each redundant bit.
Step 7: Input receiver-side data Step
Step 8: Display error and correct data
.

SOURCE CODE:

CRC:
import java.io.*;
class crc
{
public static void main(String args[]) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter Generator:");
String gen = br.readLine();
System.out.println("Enter Data:");
String data = br.readLine();
String code = data;
while(code.length() < (data.length() + gen.length() - 1))
code = code + "0";
code = data + div(code,gen);
System.out.println("The transmitted Code Word is: " + code);
System.out.println("Please enter the received Code Word: ");
String rec = br.readLine();
if(Integer.parseInt(div(rec,gen)) == 0)
System.out.println("The received code word contains no errors.");
else
System.out.println("The received code word contains errors.");
}
static String div(String num1,String num2)
{
int pointer = num2.length();
String result = num1.substring(0, pointer);
String remainder = "";
for(int i = 0; i < num2.length(); i++)
{
if(result.charAt(i) == num2.charAt(i))
remainder += "0";
else
remainder += "1";
}
while(pointer < num1.length())
{
if(remainder.charAt(0) == '0')
{
remainder = remainder.substring(1, remainder.length());
remainder = remainder + String.valueOf(num1.charAt(pointer));
pointer++;
}
result = remainder;
remainder = "";
for(int i = 0; i < num2.length(); i++)
{
if(result.charAt(i) == num2.charAt(i))
remainder += "0";
else
remainder += "1";
}
}
return remainder.substring(1,remainder.length());
}
}

HAMMING CODE:

import java.util.Scanner;
class HammingCode
{
public static void main(String arg[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the 7-bit data code");
int d[]=new int[7];
for(int i=0;i<7;i++)
{
d[i]=sc.nextInt();
}
int p[]=new int[4];
p[0]=d[0]^d[1]^d[3]^d[4]^d[6];
p[1]=d[0]^d[2]^d[3]^d[5]^d[6];
p[2]=d[1]^d[2]^d[3];
p[3]=d[4]^d[5]^d[6];
int c[]=new int[11];
System.out.println("Complete Code Word is ");
c[0]=p[0];
c[1]=p[1];
c[2]=d[0];
c[3]=p[2];
c[4]=d[1];
c[5]=d[2];
c[6]=d[3];
c[7]=p[3];
c[8]=d[4];
c[9]=d[5];
c[10]=d[6];
for(int i=0; i<11;i++)
{
System.out.print(c[i]+ " ");
}
System.out.println();
System.out.println("Enter the Received codeword");
int r[]=new int[11];
for(int i=0;i<11;i++)
{
r[i]=sc.nextInt();
}
int pr[]=new int[4];
int rd[]=new int[7];
pr[0]=r[0];
pr[1]=r[1];
rd[0]=r[2];
pr[2]=r[3];
rd[1]=r[4];
rd[2]=r[5];
rd[3]=r[6];
pr[3]=r[7];
rd[4]=r[8];
rd[5]=r[9];
rd[6]=r[10];
int s[]=new int[4];
s[0]=pr[0]^rd[0]^rd[1]^rd[3]^rd[4]^rd[6];
s[1]=pr[1]^rd[0]^rd[2]^rd[3]^rd[5]^rd[6];
s[2]=pr[2]^rd[1]^rd[2]^rd[3];
s[3]=pr[3]^rd[4]^rd[5]^rd[6];
int dec=(s[0]*1)+(s[1]*2)+(s[2]*4)+(s[3]*8);
if(dec==0)
System.out.println("No error");
else
{
System.out.println("Error is at "+dec);
if(r[dec-1]==0)
r[dec-1]=1;
else
r[dec-1]=0;
}
System.out.println("Corrected code word is :");
for(int i=0;i<11;i++)
System.out.print(r[i]+" ");
System.out.println();
}}
OUTPUT:

RESULT: Thus the error detection and error correction is implemented successfully.
Date IMPLEMENTATION OF STOP AND WAIT PROTOCOL
Expt.No:- 06

AIM: To write a java program to perform stop and wait protocol

ALGORITHM:
RECEIVER:

Step1: Start.
Step2: NextFrameExpected ← 0, repeat steps 3 forever.
Step3: If error-free frame received and sequence= NextFrameExpected, then pass packet to higher layer
and NextFrameExpected ← NextFrameExpected+1(modulo 2).
Step4: Stop.

SENDER:
Step1: sequence ← 0
Step2: Accept new packet and assign sequence to it.
Step3: Send packet sequence with sequence number sequence.
Step4: Set timer for recently sent packets.
Step5: If error free acknowledgment from receiver and NextFrameExpected -> sequence
then sequence ← NextFrameExpected.
Step6: If time out then go to step3.
Step7: Stop.

SOURCE CODE:
Receiver
import java.io.*;
import java.net.*;
public class Receiver{
ServerSocket reciever;
Socket connection=null;
ObjectOutputStream out;
ObjectInputStream in;
String packet,ack,data="";
int i=0,sequence=0;
Receiver(){}
public void run(){
try{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
reciever = new ServerSocket(2005,10);
System.out.println("waiting for connection...");
connection=reciever.accept();
sequence=0;
System.out.println("Connection established :");
out=new ObjectOutputStream(connection.getOutputStream());
out.flush();
in=new ObjectInputStream(connection.getInputStream());
out.writeObject("connected .");
do{
try{
packet=(String)in.readObject();
if(Integer.valueOf(packet.substring(0,1))==sequence){
data+=packet.substring(1);
sequence=(sequence==0)?1:0;
System.out.println("\n\nreceiver >"+packet);
}
else
{
System.out.println("\n\nreceiver >"+packet +" duplicate data");
}if(i<3){
out.writeObject(String.valueOf(sequence));i++;
}else{
out.writeObject(String.valueOf((sequence+1)%2));
i=0;
}}
catch(Exception e){}
}while(!packet.equals("end"));
System.out.println("Data recived="+data);
out.writeObject("connection ended .");
}catch(Exception e){}
finally{
try{in.close();
out.close();
reciever.close();
}
catch(Exception e){}
}}
public static void main(String args[]){
Receiver s=new Receiver();
while(true){
s.run();
}
}
}

Sender:

import java.io.*;
import java.net.*;
public class Sender{
Socket sender;
ObjectOutputStream out;
ObjectInputStream in;
String packet,ack,str, msg;
int n,i=0,sequence=0;
Sender(){}
public void run(){
try{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Waiting for Connection....");
sender = new Socket("localhost",2005);
sequence=0;
out=new ObjectOutputStream(sender.getOutputStream());
out.flush();
in=new ObjectInputStream(sender.getInputStream());
str=(String)in.readObject();
System.out.println("reciver > "+str);
System.out.println("Enter the data to send....");
packet=br.readLine();
n=packet.length();
do{
try{
if(i<n){
msg=String.valueOf(sequence);
msg=msg.concat(packet.substring(i,i+1));
}else if(i==n){
msg="end";out.writeObject(msg);break;
}out.writeObject(msg);
sequence=(sequence==0)?1:0;
out.flush();
System.out.println("data sent>"+msg);
ack=(String)in.readObject();
System.out.println("waiting for ack.....\n\n");
if(ack.equals(String.valueOf(sequence))){
i++;
System.out.println("receiver > "+" packet recieved\n\n");
}else{
System.out.println("Time out resending data....\n\n");
sequence=(sequence==0)?1:0;
}}catch(Exception e){}
}while(i<n+1);
System.out.println("All data sent. exiting.");
}catch(Exception e){}
finally{
try{
in.close();
out.close();
sender.close();
}
catch(Exception e){}
}}
public static void main(String args[]){
Sender s=new Sender();
s.run();
}
}
OUTPUT:
RESULT: Thus the program for implementing stop and wait protocol was executed successfully.
DATA:
EXPT.NO: 07 SIMULATION OF SLIDING WINDOW PROTOCOL

AIM: To Implement Simulation of Sliding Window Protocol

ALGORITHM:

Step 1:Start the program.


Step 2:Get the frame size from the user
Step 3:To create the frame based on the user request.
Step 4:To send frames to the server from the client-side.
Step 5:If your frames reach the server it will send ACK signal to client otherwise it will send a
NACK signal to the client.
Step 6:Stop the program

SOURCE CODE:
Server:

#include <sys/types.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
int main()
{
int sock,size,connect;
char senddata[50],data[50];
int val,count,i,port;
struct sockaddr_in ser,cli;
printf("\n\n Server Running ...... ");
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("\n Socket Creation Error");
exit(-1);
}
printf("\nEnter the port number : ");
scanf("%d",&port);
ser.sin_family = AF_INET;
ser.sin_port = htons(port);
ser.sin_addr.s_addr=INADDR_ANY;
bzero(&(ser.sin_zero),8);
if(bind(sock,(struct sockaddr *)&ser,sizeof(struct sockaddr)) == -1) {
perror("\n\t Error in Bind");
exit(-1);
}
if (listen(sock,2)==-1)
{
perror("\n\t Error in Listen");
exit(-1);
}
printf("\n\t Waiting for connection ");
size=sizeof(struct sockaddr);
connect=accept(sock,(struct sockaddr *)&cli,&size); if(connect==-1)
{
perror("\n\t Connection Failed :");
exit(-1);
}
printf("\n\t Connected Successfully");
printf("\n");
// get the pocket number from client
recv(connect,&val,sizeof(val),0);
count=val;
while(1)
{
i=recv(connect,&data,sizeof(data),0); data[i]='\0';
if (strcmp(data,"end")==0)
{
printf("\n\t Finished");
break;
}
if(count!=val)
{
strcpy(senddata,"packet missing");
send(connect,&count,sizeof(count),0);
send(connect,senddata,strlen(senddata),0); }
else
{
printf("\n The packet Number is : %d",val); printf("\n The data is
:%s",data);
count++;
strcpy(senddata,"send nextdata");
send(connect,&count,sizeof(count),0);
send(connect,senddata,strlen(senddata),0); }

printf("\n The Expected Packet now is: %d \n",count);


recv(connect,&val,sizeof(val),0);
}
close(connect);
close(sock);
return 0;
}
Client:

#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
int main()
{
int sock,val,i,count,port;
char recvdata[50],sentdata[50];
struct sockaddr_in server_addr;
printf("\n\n Client Running ...... ");
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("Socket");
exit(1);
}
printf("\nEnter the port number");
scanf("%d",&port);
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(port);
server_addr.sin_addr.s_addr= htonl(INADDR_ANY);
bzero(&(server_addr.sin_zero),8);
if (connect(sock, (struct sockaddr *)&server_addr, sizeof(struct sockadd r)) == -1)
{
perror("Connect");
exit(1);
}
while(1)
{
//get the pack number from client
printf("\n Enter packet number ");
scanf("%d",&val);
// sent the value to server
send(sock,&val,sizeof(val),0);
// get the data from the user
printf("\n\n Enter data ");
scanf("%s",sentdata);
// sent the to server
send(sock,sentdata,strlen(sentdata),0);
if(strcmp(sentdata,"end")==0)
break;
// recev the result from server
recv(sock,&count,sizeof(count),0);
i=recv(sock,recvdata,50,0);
recvdata[i]='\0';
printf("\n %s %d",recvdata,count);
}
close(sock);
return 0;

Output:
RESULT: Thus, the above program sliding window protocol was executed and successfully
DATA: SIMULATING ARP PROTOCOLS
EXPT.NO: 08

AIM: To write a program for simulating ARP protocols using TCP.

ALGORITHM:

Client

Step1: Start.
Step2: Using socket connection is established between client and server.
Step3: Get the IP address to be converted into a MAC address.
Step4: Send this IP address to the server.
Step5: Server returns the MAC address to client.

Server

Step 1:Start the program


Step 2:Accept the socket which is created by the client.
Step 3:Server maintains the table in which IP and corresponding MAC addresses are stored.
Step 4:Read the IP address which is sent by the client.
Step 5:Map the IP address with its MAC address and return the MAC address to the client.

SOURCE CODE:

Server

#include<sys/types.h>
#include<sys/socket.h>
#include<stdio.h>
#include<stdlib.h>
#include<netdb.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<unistd.h>
#include<string.h>
int main()
{
char ip[10][30],mac[10][30];
struct sockaddr_in saddr,caddr;
int i=0,sid,len,size,count,yes=1,q;

struct arp
{
char edesaddr[20];
char esouaddr[20];
char ftype[20];
char htype[2];
char ptype[20];
int hsize;
int psize;
int option;
char seaddr[30];
char sipaddr[30];
char tareaddr[30];
char taripaddr[30];
}
arp1;
sid=socket(AF_INET,SOCK_DGRAM,0);
if(sid<0)
{
perror("socket creation error\n");
exit(1);
}
printf("socket created\n");
saddr.sin_family=AF_INET;
saddr.sin_port=htons(1258);
saddr.sin_addr.s_addr=htonl(INADDR_ANY);
size=sizeof(caddr);
if(bind(sid,(struct sockaddr *)&saddr,sizeof(saddr))<0)
{
perror("bind error\n");
exit(1);
}
printf("binded\n");
yes=1;
while(yes)
{
printf("enter ip and mac address\n");
scanf("%s%s",ip[i],mac[i]);
i++;
printf("do u want to continue yes-1,no-0\n");
scanf("%d",&yes);
}
count=i;
yes=1;

while(yes)
{
q=recvfrom(sid,&arp1,sizeof(arp1),0,(struct sockaddr *)&caddr,&size);
if(q<0)
{
perror("receive error\n");
exit(1);
}
printf("ip received=%s\n",arp1.taripaddr);
for(i=0;i<count;i++)
{
if(strcmp(arp1.taripaddr,ip[i])==0)
{
printf("setting fields\n");
strcpy(arp1.tareaddr,arp1.seaddr);
strcpy(arp1.taripaddr,arp1.sipaddr);
strcpy(arp1.seaddr,mac[i]);
strcpy(arp1.sipaddr,ip[i]);
arp1.option=2;
break;
}
}
f:if(arp1.option==2)
{
printf("sending mac adrr\n");
q=sendto(sid,&arp1,sizeof(arp1),0,(struct sockaddr *)&caddr,size);
if(q<0)
{
perror("send error\n");
exit(1);
}
}
else
{
strcpy(ip[count],arp1.taripaddr);
printf("ip not in table\n");
printf("enter the mac addr for ip%s",arp1.taripaddr);
scanf("%s",mac[count]);
count++;
strcpy(arp1.tareaddr,arp1.seaddr);
strcpy(arp1.taripaddr,arp1.sipaddr);
strcpy(arp1.seaddr,mac[i]);
strcpy(arp1.sipaddr,ip[i]);
arp1.option=2;

goto f;
}
printf("do u want to continue1-yes\n");
scanf("%d",&yes);
}
}
Client

#include<sys/types.h>
#include<sys/socket.h>
#include<stdio.h>
#include<stdlib.h>
#include<netdb.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<unistd.h>
#include<string.h>
int main()
{
char ip[30],sip[10][30],smac[10][30];
struct sockaddr_in saddr,caddr;
int i=0,flag;
int sid,len,size,count=0,yes=1,q;
struct arp
{
char edesaddr[20];
char esouaddr[20];
char ftype[20];
char htype[2];
char ptype[20];
int hsize;
int psize;
int option;
char seaddr[30];
char sipaddr[30];
char tareaddr[30];
char taripaddr[30];
}arp1;
strcpy(arp1.edesaddr,"1111 1111");
strcpy(arp1.esouaddr,"a3:10:13:20:05:ac");
strcpy(arp1.ftype,"0x0806");
strcpy(arp1.htype,"1");
strcpy(arp1.ptype,"0x0800");
arp1.hsize=6;

arp1.psize=4;
sid=socket(AF_INET,SOCK_DGRAM,0);
if(sid<0)
{
perror("socket created error \n");
exit(1);
}
saddr.sin_family=AF_INET;
saddr.sin_port=htons(9512);
saddr.sin_addr.s_addr=htonl(INADDR_ANY);
caddr.sin_family=AF_INET;
caddr.sin_port=htons(1258);
caddr.sin_addr.s_addr=htonl(INADDR_ANY);
size=sizeof(caddr);
if(bind(sid,(struct sockaddr *)&saddr,sizeof(saddr))<0)
{
perror("bind error");
exit(1);
}
while(yes)
{
printf("enter ip address\n");
scanf("%s",ip);
for(i=0,flag=0;i<count;i++)
if(strcmp(ip,sip[i])==0)
{
printf("from cache\n");
printf("%s\n",smac[i]);
flag=1;
}
if(flag==0)
{
arp1.option=1;
strcpy(arp1.seaddr,"1111");
strcpy(arp1.sipaddr,"12:12:12:1");
strcpy(arp1.taripaddr,ip);
printf("sending data\n");
q=sendto(sid,&arp1,sizeof(arp1),0,(struct sockaddr *)&caddr,size);
if(q<0)
{
perror("send error\n");
exit(1);
}
printf("received data\n");

q=recvfrom(sid,&arp1,sizeof(arp1),0,(struct sockaddr *)&caddr,&size);


if(q<0)
{
perror("receive error\n");
exit(1);
}
printf("the mac addr for ip %s\n",arp1.sipaddr);
printf("%s\n",arp1.seaddr);
strcpy(smac[count],arp1.seaddr);
strcpy(sip[count],arp1.sipaddr);
count++;
}
printf("do u want to continue 1-yes\n");
scanf("%d",&yes);
}

OUTPUT:
RESULT: Program for simulating ARP protocols using TCP have been executed
successfully.
Date PROGRAM FOR REVERSE ADDRESS RESOLUTION
Expt.No:- 09 PROTOCOL USING UDP

AIM: To write a program for simulating RARP protocols using DCP

ALGORITHM:
Client
Step1: Start.
Step2: A connection is established between client and server.
Step3: Get the IP address to be converted into a MAC address.
Step4: Send this IP address to the server.
Step5: Server returns the MAC address to client.
Server

Step1: Start the program


Step2: Accept the connection which is created by the client.
Step3: Server maintains the table in which IP and corresponding MAC addresses
are stored.
Step4: Read the MAC address which is sent by the client.
Step5: Map the MAC address with its IP address and return the IP address to the
client. Step6: Stop.
SOURCE CODE:

Server

#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "sys/types.h"
#include "sys/socket.h"
#include "arpa/inet.h"
#include "netinet/in.h"
#define SA struct sockaddr

struct IPmac {
char ip[100];
char mac[100];
};

int main() {
int sockfd,len,i;
struct sockaddr_in servaddr;
char buff[30],temp[30],ip[30],mac[30];
int flag=0;
struct IPmac in[3]={
{"10.1.1.8","44:dd:22:11:33"},
{"127.0.0.1","33:aa:fe:4e:2d"},
{"10.1.8.5","23:a3:5d:33:9d"}
};

//printing table
printf("ip\t\tmac\n");
for(i=0;i<3;i++)
{
printf("%s\t%s\n",in[i].ip,in[i].mac);
}

//create socket
sockfd = socket(AF_INET,SOCK_DGRAM,0);

//fill structure
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(9999);
servaddr.sin_addr.s_addr = INADDR_ANY;

//bind
bind(sockfd,(SA*)&servaddr,sizeof(servaddr));

//get ip from client


len=sizeof(servaddr);

bzero(mac,sizeof(mac));
recvfrom(sockfd,mac,sizeof(mac),0,(SA*)&servaddr,&len);
printf("received mac address :%s",mac);
//store in temp
bzero(temp,sizeof(temp));
for(i=0;i<strlen(mac)-1;i++) {
temp[i]=mac[i];
}
temp[i]='\0';
bzero(ip,sizeof(ip));

//check in table
for(i=0;i<3;i++) {
if(strcmp(temp,in[i].mac)==0) {
strcpy(ip,in[i].ip);
break;
}
}
printf("ip address :%s\n",ip);
sendto(sockfd,ip,sizeof(ip),0,(SA*)&servaddr,len); return
0;
}
Client

#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "sys/types.h"
#include "sys/socket.h"
#include "arpa/inet.h"
#include "netinet/in.h"
#define SA struct sockaddr
int main() {
int sockfd,len;
char ip[30],mac[30];
struct sockaddr_in servaddr;
//creating socket
sockfd = socket(AF_INET,SOCK_DGRAM,0);
//fill structure
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(9999);
servaddr.sin_addr.s_addr = inet_addr("127.0.0.1");

len=sizeof(servaddr);

printf("RARP simulation\n");
printf("enter mac address :");
bzero(mac,sizeof(mac));
fgets(mac,sizeof(mac),stdin);
sendto(sockfd,mac,sizeof(mac),0,(SA*)&servaddr,len);
recvfrom(sockfd,ip,sizeof(ip),0,(SA*)&servaddr,&len); printf("IP address is: %s\n",ip);
return 0;
}

OUTPUT:
RESULT: Java program for simulating RARP protocols using DCP has been implemented
successfully.
Date ECHO CLIENT AND ECHO SERVER
Expt.No:- 10

AIM: To write a program for application using TCP Sockets Links.

ALGORITHM:

Server:
STEP 1: Start
STEP 2: Declare the variables for the socket
STEP 3: Specify the family, protocol, IP address and port number
STEP 4: Create a socket using socket() function
STEP 5: Bind the IP address and Port number
STEP 6: Listen and accept the client’s request for the connection
STEP 7: Read the client’s message
STEP 8: Display the client’s message
STEP 9: Close the socket
STEP 10: Stop

Client:
STEP 1: Start
STEP 2: Declare the variables for the socket
STEP 3: Specify the family, protocol, IP address and port number
STEP 4: Create a socket using socket() function
STEP 5: Call the connect() function
STEP 6: Read the input message
STEP 7: Send the input message to the server
STEP 8: Display the server’s echo
STEP 9: Close the socket
STEP 10: Stop

CODE:
Server
#include<stdio.h>
#include<unistd.h>
#include<netinet/in.h>
#include<netdb.h>
#define SERV_TCP_PORT 5035
int main(int argc,char**argv)
{
int sockfd,newsockfd,clength;
struct sockaddr_in serv_addr,cli_addr;
char buffer[4096];
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);
printf("\nStart");
bind(sockfd,(struct sockaddr*)&serv_addr,sizeof(serv_addr));
printf("\nListening");
printf("\n");
listen(sockfd,5);
clength=sizeof(cli_addr);
newsockfd=accept(sockfd,(struct sockaddr*)&cli_addr,&clength);
printf("\nAccepted..");
printf("\n");
read(newsockfd,buffer,4096);
printf("\nClient mesage:%s",buffer);
write(newsockfd,buffer,4096);
printf("\n");
close(sockfd);
return 0;
}

Client

#include<stdio.h>
#include<arpa/inet.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<netdb.h>
#include<unistd.h>
#define SERV_TCP_PORT 5035
int main(int argc,char**argv[])
{
int sockfd;
struct sockaddr_in serv_addr;
struct hostent *server;
char buffer[4096];
sockfd=socket(AF_INET,SOCK_STREAM,0);
serv_addr.sin_family=AF_INET;
serv_addr.sin_addr.s_addr=inet_addr("127.0.0.1");
serv_addr.sin_port=htons(SERV_TCP_PORT);
printf("\nReady to Send");
connect(sockfd,(struct sockaddr*)&serv_addr,sizeof(serv_addr));
printf("\nEnter Message to send\n");
printf("\nClient:");
fgets(buffer,4096,stdin);
write(sockfd,buffer,4096);
printf("ServerEcho:%s",buffer);
printf("\n");
close(sockfd);
return 0;
}
OUTPUT:

RESULT: Program for application using TCP Sockets Links is implemented


successfully
Date TCP CHAT
Expt.No:- 11

AIM: Write a Program client –server application for chat using TCP Sockets

Algorithm:
Server:
Step 1: Start
Step 2: Declare the variables for the socket.
Step 3:Specify the family, protocol, IPaddress and port number.
Step 4 :Create a socket using socket() function.
Step 5: Bind the IP address and port number.
Step 6: Listen and accept the client’s request for the connection.
Step 7: Read the client’s message.
Step 8: Display the client’s message.
Step 9: Continue the chat
Step 10: Terminate the chat
Step 11: Close the socket.
Step 12: Stop

Client:

Step 1: Start
Step 2: Declare the variables for the socket
Step 3: Specify the family, protocol IP address and port number.
Step 4: Create a socket() using socket() function
Step 5: Call the connect() function
Step 6: Read the input message.
Step 7: Send the input message to the server.
Step 8: Display the server’s reply
Step 9: Continue the chat.
Step 10: Terminate the chat.
Step 11: Close the socket.
Step 12: Stop.
SOURCE CODE:
Server

#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<netdb.h>
#define SERV_TCP_PORT 5034
int main(int argc,char**argv)
{
int sockfd,newsockfd,clength;
struct sockaddr_in serv_addr,cli_addr;
char buffer[4096];
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);
bind(sockfd,(struct sockaddr*)&serv_addr,sizeof(serv_addr));
listen(sockfd,5);
clength=sizeof(cli_addr);
newsockfd=accept(sockfd,(struct sockaddr*)&cli_addr,&clength);
read(newsockfd,buffer,4096);
while(buffer!="quit")
{
printf("\nClient message: %s",buffer);
printf("\nType your message : ");
fgets(buffer,4096,stdin);
write(newsockfd,buffer,4096);
printf("\n");
read(newsockfd,buffer,4096);
}
close(sockfd);
return 0;
}

Client

#include<stdio.h>
#include<unistd.h>
#include<arpa/inet.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<netdb.h>
#define SERV_TCP_PORT 5034
int main(int argc,char**argv)
{
int sockfd;
struct sockaddr_in serv_addr;
struct hostent *server;
char buffer[4096];
sockfd=socket(AF_INET,SOCK_STREAM,0);
serv_addr.sin_family=AF_INET;
serv_addr.sin_addr.s_addr=inet_addr("127.0.0.1");
serv_addr.sin_port=htons(SERV_TCP_PORT);
connect(sockfd,(struct sockaddr*)&serv_addr,sizeof(serv_addr));
printf("\nEnter the message to send : ");
fgets(buffer,4096,stdin);
fputs(buffer,stdout);
while(buffer!="quit")
{
if(buffer=="quit")
break;
write(sockfd,buffer,4096);
read(sockfd,buffer,4096);
printf("\n");
printf("\nServer message:\t%s",buffer);
printf("\nType your message:\t");
fgets(buffer,4096,stdin);
}
close(sockfd);
return(0);
}
OUTPUT:

RESULT: Thus, the client –server application for chat using TCP Sockets is implemented
successfully.
Date TCP FILE TRANSFER
Expt.No:-12

AIM: Write a program for transferring of files from client to server

ALGORITHM:
Server:

Step1: Start
Step2: Declare the variables and structures required.
Step 3: The socket is created using the socket function.
Step 4: The socket is binded to the specific port.
Step 5: Start listening for the connections.
Step6: Accept the connection from the client.
Step 7: Create a new file.
Step 8: Receives the data from the client.
Step 9: Write the data into the file.
Step 10: Stop.

Client:

Step 1: Start.
Step 2: Declare the variables and structures required.
Step 3: A socket is created and the connect function is executed.
Step 4: The file is opened.
Step 5: The data from the file is read and sent to the server.
Step 6: The socket is closed.
Step 7: Stop.

SOURCE CODE:
Client

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#define SIZE 1024
void write_file(int sockfd){
int n;
FILE *fp;
char *filename = "recv.txt";
char buffer[SIZE];
fp = fopen(filename, "w");
while (1) {
n = recv(sockfd, buffer, SIZE, 0);
if (n <= 0){
break;
return;
}
fprintf(fp, "%s", buffer);
bzero(buffer, SIZE);
}
return;
}
int main(){
char *ip = "127.1.0.1";
int port = 8080;
int e;
int sockfd, new_sock;
struct sockaddr_in server_addr, new_addr;
socklen_t addr_size;
char buffer[SIZE];
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if(sockfd < 0) {
perror("[-]Error in socket");
exit(1);
}
printf("[+]Server socket created successfully.\n");
server_addr.sin_family = AF_INET;
server_addr.sin_port = port;
server_addr.sin_addr.s_addr = inet_addr(ip);
e = bind(sockfd, (struct sockaddr*)&server_addr, sizeof(server_addr));
if(e < 0) {
perror("[-]Error in bind");
exit(1);
}
printf("[+]Binding successfull.\n");
if(listen(sockfd, 10) == 0){
printf("[+]Listening....\n");
}else{
perror("[-]Error in listening");
exit(1);
}
addr_size = sizeof(new_addr);
new_sock = accept(sockfd, (struct sockaddr*)&new_addr, &addr_size);
write_file(new_sock);
printf("[+]Data written in the file successfully.\n");
return 0;
}

Server

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <arpa/inet.h>
#define SIZE 1024
void send_file(FILE *fp, int sockfd){
int n;
char data[SIZE] = {0};
while(fgets(data, SIZE, fp) != NULL) {
if (send(sockfd, data, sizeof(data), 0) == -1) {
perror("[-]Error in sending file.");
exit(1);
}
bzero(data, SIZE);
}
}
int main(){
char *ip = "127.1.0.1";
int port = 8080;
int e;
int sockfd;
struct sockaddr_in server_addr;
FILE *fp;
char *filename = "send.txt";
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if(sockfd < 0) {
perror("[-]Error in socket");
exit(1);
}
printf("[+]Server socket created successfully.\n");
server_addr.sin_family = AF_INET;
server_addr.sin_port = port;
server_addr.sin_addr.s_addr = inet_addr(ip);
e = connect(sockfd, (struct sockaddr*)&server_addr, sizeof(server_addr));
if(e == -1) {
perror("[-]Error in socket");
exit(1);
}
printf("[+]Connected to Server.\n");
fp = fopen(filename, "r");
if (fp == NULL) {
perror("[-]Error in reading file.");
exit(1);
}
send_file(fp, sockfd);
printf("[+]File data sent successfully.\n");
printf("[+]Closing the connection.\n");
close(sockfd);
return 0;
}
OUTPUT:

RESULT: Thus the transferring of files from client to server is implemented successfully.
Date SIMULATION OF DNS USING UDP SOCKETS
Expt.No:- 13

AIM: To write a java program for DNS application

Algorithm:
Server:
Step 1: Start.
Step 2: Create a UDP socket.
Step 3: Receive canonical address from server.
Step 4: Send DNS to Client.
Step 5: Stop.

Client:
Step 1: Start.
Step 2: Create a UDP socket.
Step 3: Send a canonical address to the server.
Step 4: Display DNS.
Step 5: Stop.

SOURCE CODE:
Server
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<string.h>
#include<netinet/in.h>
#include<netdb.h>
#define PORT 1981
#define BACKLOG 15
int main()
{
int fd2,fd;
FILE *f1;
struct
{
char dname[30];
char ipaddr[16];
}address;
struct sockaddr_in server;
struct sockaddr_in client;
char buf[50],res[50],buf1[55];
int sin_size;
if((fd=socket(AF_INET,SOCK_STREAM,0))==-1)
{
printf("error in socket creation");
exit(-1);
}
bzero(&(client.sin_zero),8);
server.sin_family=AF_INET;
server.sin_port=htons(PORT);
server.sin_addr.s_addr=htonl(INADDR_ANY);
if((bind(fd,(struct sockaddr *)&server,sizeof(server)))==-1)
{
printf("bind error");
exit(-1);
}
if(listen(fd,BACKLOG)==-1)
{
printf("listen() error");
exit(-1);
}
sin_size=sizeof(client);
if((fd2=accept(fd,(struct sockaddr *)&client,&sin_size))<0)
{
printf("accept error");
exit(-1);
}
printf("connection is got");
do
{
recv(fd2,buf,50,0);
printf("\n IP requested for the domain name%s\t",buf);
f1=fopen("destination.txt","r");
while(!feof(f1))
{
fscanf(f1,"%s%s",address.dname,address.ipaddr);
if(strcmp(buf,address.dname)==0)
{
printf("\nThe IP Address is : %s",address.ipaddr);
strcpy(res,address.ipaddr);
break;
}
else
strcpy(res,"NIL");
}
fclose(f1);
printf("\n the ipaddress:%s\t");
send(fd2,res,50,0);
}while((strcmp(buf,"exit"))!=0);
close(fd2);
}

Client

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<string.h>
#include<netinet/in.h>
#include<netdb.h>
#define PORT 1981
#define MAXDATASIZE 100
int main()
{
int fd1,numbytes=0;
struct sockaddr_in server;
char buf[MAXDATASIZE],buf1[50];
if((fd1=socket(AF_INET,SOCK_DGRAM,0))==-1)
{
printf("socket() error");
exit(-1);
}
bzero(&(server.sin_zero),8);
server.sin_family=AF_INET;
server.sin_port=htons(PORT);
server.sin_addr.s_addr=INADDR_ANY;
if((connect(fd1,(struct sockaddr *)&server,sizeof(server)))<0)
{
printf("connection error");
exit(-1);
}
do
{
printf("\n enter the domain name\n");
scanf("%s",buf);
send(fd1,buf,50,0);
recv(fd1,buf1,50,0);
printf("\nThe ipaddress is:%s\t",buf1);
}
while(strcmp(buf,"exit")!=0);
close(fd1);
exit(0);
OUTPUT:

RESULT : Applications using TCP and UDP Sockets like DNS, SNMP and File Transfer is
done successfully.

You might also like