Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
655 views

Computer Networks Lab File

The document contains code to simulate the Address Resolution Protocol (ARP) and Reverse Address Resolution Protocol (RARP) by implementing an ARP server program that uses shared memory to store IP address and MAC address mappings for 3 devices, with the server program able to respond to ARP requests for address resolution.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
655 views

Computer Networks Lab File

The document contains code to simulate the Address Resolution Protocol (ARP) and Reverse Address Resolution Protocol (RARP) by implementing an ARP server program that uses shared memory to store IP address and MAC address mappings for 3 devices, with the server program able to respond to ARP requests for address resolution.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

Lloyd Institute of Engineering & Technology, Greater Noida

(Affiliated to Dr. A.P.J. Abdul Kalam Technical University, Uttar Pradesh)

Practical File
of
Computer Network Lab
(KCS 653)
for
B. Tech. in Computer Science & Engineering
(3rd Year, 6th Semester)
(2021-22)

Submitted to: Submitted by:


Mrs. Shweta Chauhan Hemant kumar
1901530100014
LIST OF EXPERIMENTS

S. no. Experiments
1 To study the Cross-Wired and Straight through network cables.
2
Implementation of Stop and Wait Protocol and Sliding Window
Protocol.
3
Study of Socket Programming and Client – Server model.
4
Write a code simulating ARP /RARP protocols.
5
Write a code simulating PING and TRACEROUTE commands.
6
Create a socket for HTTP for web page upload and download.
7 Write a program to implement RPC (Remote Procedure Call).

8
Implementation of Subnetting.
9 Applications using TCP Sockets like a. Echo client and echo server b.
Chat c. File Transfer.
10 Applications using TCP and UDP Sockets like
d. DNS e. SNMP f. File Transfer.

HEMANT KUMAR | 1901530100014 | B.TECH CSE 3rd YEAR


PROGRAM: 1

Aim: To study the Cross-Wired and Straight through network cables.

What is an Ethernet cable?


An Ethernet cable is a network cable used for high-speed wired network connections between two
devices. This network cable is made of four-pair cable, which is consists of twisted pair conductors.
It is used for data transmission at both ends of the cable, which is called RJ45 connector.

The Ethernet cables are categorized as Cat 5, Cat 5e, Cat 6, and UTP cable. Cat 5 cable can support
a 10/100 Mbps Ethernet network while Cat 5e and Cat 6 cable to support Ethernet.

What is Straight Through Cable?

Straight Through Cable

Straight-through cable is a type of CAT5 with RJ-45 connectors at each end, and each has the same
pin out. It is in accordance with either the T568A or T568B standards. It uses the same color code
throughout the LAN for consistency. This type of twisted-pair cable is used in LAN to connect a
computer or a network hub such as a router. It is one of the most common types of network cable.

What Is Crossover Cable?

Crossover Cable
A Crossover cable is a type of CAT 5 where one end isT568A configuration and the other end as
T568BConfiguration. In this type of cable connection, Pin 1 is crossed with Pin 3, and Pin 2 is
crossed with Pin 6.
HEMANT KUMAR | 1901530100014 | B.TECH CSE 3rd YEAR
Crossover cable is used to connect two or more computing devices. The internal wiring of crossover
cables reverses the transmission and receive signals. It is widely used to connect two devices of the
same type: e.g., two computers or two switches to each other.

In regard to physical appearance, Crossover Ethernet cables are very much similar to regular
Ethernet cables. Still, they are different with regard to the order with which the wires are arranged.
This type of Ethernet cable is made to connect to network devices of the same kind over Ethernet
directly. Crossover cables are mostly used to connect two hosts directly.

When to use Straight Through Cable?

Computer to network switch/hub

Here are applications where you should use Crossover Cable:

• It helps you to connect a computer to a switch/hub’s normal port.


• You can use it to connect a computer to a cable/DSL modem’s LAN port.
• It allows you to connect a router’s WAN port to a cable/DSL modem’s LAN port.
• Connect 2 switches or hubs with one of the hub or switch using an upline port and the other
one using a normal port.

HEMANT KUMAR | 1901530100014 | B.TECH CSE 3rd YEAR


When to use Crossover Cable?

Use of Cross over cable- computer to computer

Router to Router
Here is an application where you should use Crossover Cable:

• It can use a computer to a computer with no switch or hub.


• Network devise to the network device. For example, the route to the router.
• Crossover cable enables one to establish a direct connection between two computing devices
using Ethernet ports.
• It Connects two computers directly.
• You can connect two hubs/switches by using the normal port in both switches and hubs.

HEMANT KUMAR | 1901530100014 | B.TECH CSE 3rd YEAR


PROGRAM: 2

Aim: Implementation of Stop and Wait Protocol and Sliding Window Protocol.

Simulation of Sliding Window Protocol

#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int k,time,win=2,i2=0,frame=0,a[20],b[20],i,j,s,r,ack,c,d;
int send(int,int);
int receive();
int checsum(int *);
main()
{
int i1=0,j1=0,c1;
printf("Enter the frame size\n");
scanf("%d",&frame);
printf("Enter the window size\n");
scanf("%d",&win);
j1=win;
for(i=0;i<frame;i++)
a[i]=rand(); } k=1;

while(i1<frame)

{
if((frame-i1)<win)

j1=frame-i1;

printf("\n\ntransmit the window no


%d\n\n",k); c1=send(i1,i1+j1);

ack=receive(i1,i1+j1,c1);
if (ack!=0)

{
printf("\n\n1.Selective window\n");
printf("2.Go back N\n");
scanf("%d",&ack);
switch(ack)
{
case 1:
printf("\n\n\t Selective window \t\nEnter the faulty frame no\n");
scanf("%d",&i2);
printf("\n\n Retransmit the frame %d \n",i2);
send(i2,i2+1);
break; case 2:
HEMANT KUMAR | 1901530100014 | B.TECH CSE 3rd YEAR
printf("\n\n\t Go back n\t\n\n");
printf("\nRetransmit the frames from %d to %d\n",i1,i1+j1);
send(i1,i1+j1);
break;
}
}
i1=i1+win;
k++;
}
}
int send(c,d)
{
int t1;
for(i=c;i<d;i++)
{
b[i]=a[i];
printf("frame %d is sent\n",i);
}
s=checsum(&a[c]);
return(s);
}
int receive(c,d,c2)
int c2;
{ r=checsum(&b[c]);
if(c2==r)
{
return(0);
}
else return(1);
}
int checsum(int *c)
{
int sum=0;
for(i=0;i<win;i++)
sum=sum^(*c);
return sum;
}

HEMANT KUMAR | 1901530100014 | B.TECH CSE 3rd YEAR


Output:
Enter the frame size
50
Enter the window size
5
transmit the window no 1
frame 0 is sent
frame 1 is sent
frame 2 is sent
frame 3 is sent
frame 4 is sent

1.selective window
2.Go back N

1 selective window
enter the faculty frame no
15
retransmit the frames from 15
frame 15 is sent
transmit the window no 2
frame 5 is sent
frame 6 is sent
frame 7 is sent
frame 8 is sent
frame 9 is sent

1.selective window
2.Go back N

HEMANT KUMAR | 1901530100014 | B.TECH CSE 3rd YEAR


PROGRAM: 3

Aim: Study of Socket Programming and Client – Server model:

#include<iostream.h>
#include<stdio.j>
#include<sys/socket.h>
#include<netinet/in.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#includ<netdb.h>
#include<arpa/inet.h>
#include<sys/types.h>
#includ<time.h>
int main()
{
int listenfd,connfd,n;
struct sockaddr_in serv;
char buff[100];
int port=1058;
listenfd=socket(AF_INET,SOCK_STREAM,0);
bzero(&serv,sizeof(serv));
serv.sin_family=AF_INET;
serv.sin_addr.s_addr=htonl(INADDR_ANY);
serv.sin_port=htons(port);
bind(listenfd,(struct sockaddr*)&serv,sizeof(serv));
listen(listenfd,15);
while(1) { connfd=accept(listenfd,(struct sockaddr*)NULL,NULL);
cout<<"\nConx.Open!]n";
int child;
if((child=fork())<<"\nChild disaster!";
exit(1);
}
else if(child==0)
{
close(listenfd);
strcpy(buff,"abc");
while(strcmp(buff,"bye")!=0)
{
if(strcmp(buff,"bye")==0)
break; n=read(connfd,buff,100);
buff[n]='\0';
cout<<"\nClient:"<<<"Server:";
gets(buff);
write(connfd,buff,strlen(buff));
}
cout<<"\n\n Conx closed!";
close(connfd);
exit(0);
HEMANT KUMAR | 1901530100014 | B.TECH CSE 3rd YEAR
}
close(connfd);
}
return 0;
}

Client Program:-

#include<iostream.h>
#include<stdio.j>
#include<sys/socket.h>
#include<netinet/in.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#includ<netdb.h>
#include<arpa/inet.h>
#include<sys/types.h>
#includ<errno.h>
#define MAX 100
main(int argc.char*argv)
{
int sockfd,n;
char buff[100];
struct sockaddr_in serv;
if(argc!=3)
{
printf("\n Error ! usage:./a.out\n");
exit(0);
}
if((sockfd=socket(AF_INET,SOCK_STREAM,0))<0)
{

printf("\n Error ! Socket not created...\n")


exit(0);
}
bzero(&serv,sizeof(serv));
serv.sin_family=AF_INET;
serv.sin_port=htons(atoi9argv[2]));
if(inet_pton(AF_INET,argv[1],&serv.sin_addr)<0)
{
printf("\n Errorin conversion of IP address from string to num\n");
exit(0);
}
if(connect(sockfd,(struct sockaddr*)&serv,sizeof(serv))<0)
{
printf("\n Error ! can not established...\n");
exit (0);
}
printf("\n connected..\n");
HEMANT KUMAR | 1901530100014 | B.TECH CSE 3rd YEAR
strcpy(buff,"abc");
while(strcmp(buff,"bye")!=0)
{
cout<<"\n Client:"; gets(buff);
write(sockfd,buff,strlen(buff)); cout<<"\n Server:";
n=read(sockfd,buff,100);
buff[n]='\0'; cout<<0)
{
cout<<"\n Read Error";
exit (0);
}
}
cout<<"\n";
return 0;
}

HEMANT KUMAR | 1901530100014 | B.TECH CSE 3rd YEAR


PROGRAM: 4
Aim: Write a code simulating ARP /RARP protocols.

Variation 1) //ARP SERVER


#include<stdio.h>
#include<sys/types.h>
#include<sys/shm.h>
#include<string.h>
main()
{
int shmid, 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';
printf("\n ARP table at serverside is=\n%s", shmptr); shmdt(shmptr);
}
ARP table at serverside 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

//ARP CLIENT
#include<stdio.h>
#include<sys/types.h>
#include<sys/shm.h>
#include<string.h>
Main()
{
int shmid,a;
char *ptr, *shmptr;
char ptr2[51], ip[12], mac[26]; shmid=shmget(3000,10,0666);
shmptr=shmat(shmid,NULL,0);
puts("the arp table is");
printf("%s",shmptr);
printf("\n1.ARP\n 2.RARP\n 3.EXIT\n");
scanf("%d",&a);
HEMANT KUMAR | 1901530100014 | B.TECH CSE 3rd YEAR
switch(a)
{
case 1:
puts("enter ip address");
scanf("%s",ip);
ptr=strstr(shmptr, ip);
ptr-=8;
sscanf(ptr,"%s%*s",ptr2);
printf("mac addr is %s",ptr2);
break;
case 2:
puts("enter mac addr");
scanf("%s",mac); ptr=strstr(shmptr, mac);
sscanf(ptr,"%*s%s",ptr2);
printf("%s",ptr2);
break;
case 3:
exit(1);
}
}

HEMANT KUMAR | 1901530100014 | B.TECH CSE 3rd YEAR


SAMPLE INPUT 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
ip addr is 5.6.7.8

Variation 2)
#include<sys/socket.h>
#include< netinet/in.h>
#include<arpa/in.h>
main()
{
char host[17],*ptr;
long int addr;
struct in_addr ad; /* netinet/in.h*/ puts("\n\nEnter the host ID");
gets(host);
addr= inet_addr(host); /*convert dotted decimal notation to 32-bit ip addres*/ puts("\n\n32 Bit IP
address is:");
printf("\n\n%d",addr);
puts("\n\nEnter the 32 bit ip address :\n");
scanf("%d",&ad.s_addr); ptr=inet_ntoa(ad); /*convert ip to dotted decimal*/ puts("\n\nHost ip
address is");
printf("\n%s",ptr);
}

HEMANT KUMAR | 1901530100014 | B.TECH CSE 3rd YEAR


PROGRAM: 5

Aim: Write a code simulating PING and TRACEROUTE commands

PING:

Variation 1)

int main()

const char *hostName = [@"stackoverflow.com" cStringUsingEncoding:NSASCIIStringEncoding];


SCNetworkConnectionFlags flags = 0;

if (SCNetworkCheckReachabilityByName(hostName, &flags) && flags > 0)

NSLog(@"Host is reachable: %d", flags);

Else

NSLog(@"Host is unreachable");

Variation 2)

bool success = false;

const char *host_name = [@"stackoverflow.com"


cStringUsingEncoding:NSASCIIStringEncoding]; SCNetworkReachabilityRef reachability =
SCNetworkReachabilityCreateWithName(NULL, host_name);

SCNetworkReachabilityFlags flags;

success = SCNetworkReachabilityGetFlags(reachability, &flags);

bool isAvailable = success && (flags & kSCNetworkFlagsReachable) && !(flags &
kSCNetworkFlagsConnectionRequired);

if (isAvailable)

HEMANT KUMAR | 1901530100014 | B.TECH CSE 3rd YEAR


NSLog(@"Host is reachable: %d", flags);

Else

NSLog(@"Host is unreachable");

HEMANT KUMAR | 1901530100014 | B.TECH CSE 3rd YEAR


PROGRAM: 6

Aim: Create a socket for HTTP for web page upload and download

#include<sys/socket.h>
#include<netinet/in.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#includ<netdb.h>
#include<arpa/inet.h>
#define size 100

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

struct sockaddr_in sock;

struct hostent *hp,port; char *req,*hostname,*cp;

FILE *local;

char buff[size];

int con,i,l,nrv,sd;

if(argc!=3)

printf(“\nUsage: %sfilename”,argv[0]);

exit(1);

if(cp=strchr(argv[1],’/’))

*cp=’\0’; l=strlen(argv[1]);

hostname=malloc(l+1);

strcpy(hostname,argv[1]);

*cp=’/’;

l=strlen(cp); req=malloc(l+1);

strcpy(req,cp);

HEMANT KUMAR | 1901530100014 | B.TECH CSE 3rd YEAR


}

else

hostname=argv[1];

req=”/”;

printf(“\nHost=%s\nReq= %s”,hostname,req);

sd=socket(AF_INET,SOCK_STREAM,0);

if(sd<0)

perror(“\nCannot open socket”);

exit(1);

bzero(&sock,sizeof(sock));
sock.sin_family=AF_INET;
con=inet_pton(AF_INET, argv[1], &sock);
sock.sin_port=htons(80);

con=connect(sd,(struct sockaddr *)&sock, sizeof(sock));


if(con<0)

perror(“\nConnection failed”);
exit(1);

sprintf(buff,”Get HTTP:%s//1.1\r\nHost: %s\r\nConnection: class\r\n\r”, req, hostname);


printf(“Buff=%s\n”, buff);
l=strlen(buff);
local=fopen(argv[2],”w”);
write(sd,buff,1);
do

nrv=read(sd,buff,size);
if(nrv>0)

HEMANT KUMAR | 1901530100014 | B.TECH CSE 3rd YEAR


{
for(i=0;i<nrv;i++)
putc(buff[i],local);

}
else break;
}
while(1);
close(sd);
fclose(local);
return 0;
}

HEMANT KUMAR | 1901530100014 | B.TECH CSE 3rd YEAR


PROGRAM: 7

Write a program to implement RPC (Remote Procedure Call)

REMOTE PROCEDURE CALL

AIM: To write a network program to call the Remote running process.

ALGORITHM:Step 1: Start the program


Step 2: Implement the operation to be in the procedure.
Step 3: In server side. register list of performance object in the RMI registry
Step 4: By starting the RMI registry we can run our server program to keep the program run always.
Step 5: If the client want to involve to the procedure by means that by biding the registered object in
the RMI registry if(client) call the procedure and produce the result..
Step 6: Stop the program.

Program 1 for RPC (Interface):


import java.rmi.*;
public interface greater extends Remote
{
public String getresult(int first,int second)throws RemoteException;
}

RPC Program for client:


import java.io.*;
import java.rmi.*;
public class great
{
public static void main(String args[]) throws IOException
{
String result;
int n=0,n1=0;
try
{
greater f=(greater)Naming.lookup("greaterser");
try
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("\n\n\t Rpc program for clientside");
System.out.println("\n\n\t ******************************");
System.out.println("\n\t Enter the two numbers");
System.out.println("\n\t the First number is :");
n=Integer.parseInt(br.readLine());
System.out.println("\n\t the Second number is:");
n1=Integer.parseInt(br.readLine());
}
catch(IOException e)
{
}
result=f.getresult(n,n1);
if(result.equals("Equal"))
HEMANT KUMAR | 1901530100014 | B.TECH CSE 3rd YEAR
System.out.println("\n\n\t Both nos are equal");
else
System.out.println("\n\n\t The greater no is"+result);
}
catch(Exception e)
{
System.out.println("Exception from client side:"+e);
}}}

RPC Program for server:


import java.io.*;
import java.rmi.*;
import java.rmi.server.*;
import java.util.*;
public class greaterser extends UnicastRemoteObject implements greater
{
public greaterser()throws RemoteException{}
public String getresult(int first,int second)throws RemoteException
{
if(first<second)
return(Integer.toString(second));
else
{
if(second<first)
return(Integer.toString(first));
else
return("EQUAL");
}
}
public static void main(String args[])
{
try
{
greaterser f=new greaterser();
Naming.rebind("greaterser",f);
System.out.println("\n\n\t Server is ready");
}
catch(Exception e)
{
System.out.println("error from ss");
}
}
}

HEMANT KUMAR | 1901530100014 | B.TECH CSE 3rd YEAR


OUTPUT:

RESULT:
Thus the program was executed and output is verified successfully.

HEMANT KUMAR | 1901530100014 | B.TECH CSE 3rd YEAR


PROGRAM: 8

Aim: Implementation of Subnetting

dot-decimal address binary representation Full IP Address 192.168.5.10


11000000.10101000.00000101.00001010 Subnet Mask 255.255.255.0
11111111.11111111.11111111.00000000 \\ and these bits to get the Network Address. Note, the
prefix could be used \\ instead of subnet mask - they represent the same thing. Network Address
192.168.5.0 11000000.10101000.00000101.00000000 \\ Host and prefix Host Portion 0.0.0.10
00000000.00000000.00000000.00001010 Prefix /24 11111111.11111111.11111111.00000000

HEMANT KUMAR | 1901530100014 | B.TECH CSE 3rd YEAR


PROGRAM 9

Applications using TCP Sockets like

a. Echo client and echo server

IMPLEMENTATION OF ECHO SERVER

AIM: To Write a Network Socket program for implementing the echo operation.

ALGORITHM:

TCP Echo Server

1. Include necessary header files to support functions for Socket definitions,Socket types,Internet
addresses,I/O functions,UNIX system calls.
2. Declare variables for Socket ID,Port number,Socket addresses,Character buffer etc.
3. Create socket for server and bind socket with addresses.
4. Specify number of allowed connections.
5. Wait for connection.
6. Accept connection if any.
7. Retrieve information from Connected Socket.
8. Echo retrieved information to Connected Socket.
9. Close Connected Socket.

TCP Echo Client

1. Include necessary header files to support functions for Socket definitions,Socket types,Internet
addresses,I/O functions,UNIX system calls.
2. Declare variables for Socket ID,Port number,Socket addresses,Character buffer etc.
3. Create socket for client.
4. Connect client socket to the server socket addresses.
5. Give message to be echoed.
6. Retrieve echoed information from server and display it.

SERVER PROGRAM:
import java.io.*;
import java.net.*;
import java.lang.String.*;
public class Secho
{

public static void main(String args[]) throws Exception


{
ServerSocket ss =new ServerSocket(123);
Socket s=ss.accept();
DataInputStream in= new DataInputStream(s.getInputStream());
DataOutputStream out=new DataOutputStream(s.getOutputStream());
String str;
HEMANT KUMAR | 1901530100014 | B.TECH CSE 3rd YEAR
System.out.println("\nSERVER SIDE!...");

while(true)
{
str=in.readLine();
out.writeBytes(str+"\n");
System.out.println("Msg from Client");
System.out.println(str+"\n");
}
}
}

CLIENT PROGRAM:
import java.io.*;
import java.net.*;
import java.lang.String.*;
public class Cecho
{
public static void main(String args[]) throws Exception
{
DataInputStream in=new DataInputStream (System.in);
Socket s=new Socket("LocalHost",123);
DataInputStream inecho=new DataInputStream(s.getInputStream());
DataOutputStream out=new DataOutputStream(s.getOutputStream());
String str;
System.out.println("\nCLIENT SIDE!...\nType EXIT TO QUIT\nEnter Client Msg");
while((str=in.readLine())!=null)
{
out.writeBytes(str+"\n");
if(str.equals("exit"))
{
out.writeBytes("\nClient Terminated");
break;
}
Else{
System.out.println("\nEcho From Server");
System.out.print(str+"\n");
System.out.println("\nCLIENT SIDE!...\nEnter Client Msg");
}
}
}
}

HEMANT KUMAR | 1901530100014 | B.TECH CSE 3rd YEAR


OUTPUT:

SERVER:

CLIENT:

RESULT:
Thus the program was executed and output is verified successfully.

b. Chat

CHAT APPLICATION

AIM: To write a network program for implementing chat using TCP socket.

HEMANT KUMAR | 1901530100014 | B.TECH CSE 3rd YEAR


ALGORITHM:
1. Client sends the request to server
2. Server runs the request and the connection with the client that has requested the server.
3. The client sends the message to server.
4. The server process it and it is displayed (ie) replier by sending the message to client also
displayed.
5. Stop the program.

SERVER PROGRAM:
import java.io.*;
import java.net.*;
public class chatserver
{
public static void main(String args[])throws Exception
{
DataInputStream din=null;
DataOutputStream dout=null;
Socket c=null;
ServerSocket m=null;
DataInputStream stdin=new DataInputStream(System.in);
try
{
m=new ServerSocket(68);
c=m.accept();
din=new DataInputStream(c.getInputStream());
dout=new DataOutputStream(c.getOutputStream());
}
catch(Exception e)
{
}
while(c!=null)
{
String m2;
System.out.println("Server");
while(true)
{
String m1=din.readLine();
System.out.println("Message from client.."+m1);
System.out.println("\n\n Enter the message...");
m2=stdin.readLine();
dout.writeBytes(""+m2);
dout.writeBytes("\n");
}
}
din.close();
dout.close();
c.close();
m.close();
HEMANT KUMAR | 1901530100014 | B.TECH CSE 3rd YEAR
}
}

CLIENT PROGRAM:
import java.io.*;
import java.net.*;
public class chatclient
{
public static void main(String args[])throws Exception
{
Socket c=null;
DataInputStream uin=null;
DataInputStream din=null;
DataOutputStream dout=null;
try
{
c=new Socket("localhost",68);
uin=new DataInputStream(System.in);
din=new DataInputStream(c.getInputStream());
dout=new DataOutputStream(c.getOutputStream());
}
catch(Exception e)
{
}
if(c!=null)
{
String inp;
System.out.println("Enter the message:");
while((inp=uin.readLine())!=null)
{
dout.writeBytes(""+inp);
dout.writeBytes("\n");
System.out.println("Echoed message from server.."+din.readLine());
System.out.println("Enter ur message:");
}
}
din.close();
dout.close();
c.close();
}
}

OUTPUT:

SERVER:

HEMANT KUMAR | 1901530100014 | B.TECH CSE 3rd YEAR


CLIENT:

RESULT:
Thus the program was executed and output is verified successfully.

c. File Transfer
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
HEMANT KUMAR | 1901530100014 | B.TECH CSE 3rd YEAR
#include <errno.h>
#include <arpa/inet.h>
int main(void)
{
int sockfd = 0;
int bytesReceived = 0;
char recvBuff[256];
memset(recvBuff, '0', sizeof(recvBuff));
struct sockaddr_in serv_addr;
/* Create a socket first */
if((sockfd = socket(AF_INET, SOCK_STREAM, 0))< 0)
{
printf("\n Error : Could not create socket \n");
return 1;
}
/* Initialize sockaddr_in data structure */
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(5000); // port
serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
/* Attempt a connection */
if(connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr))<0)
{
printf("\n Error : Connect Failed \n");
return 1;
}
/* Create file where data will be stored */
FILE *fp;
fp = fopen("sample_file.txt", "ab");

if(NULL == fp)
{
printf("Error opening file");
return 1;
}
/* Receive data in chunks of 256 bytes */
while((bytesReceived = read(sockfd, recvBuff, 256)) > 0)
{
printf("Bytes received %d\n",bytesReceived);
// recvBuff[n] = 0;
fwrite(recvBuff, 1,bytesReceived,fp);

// printf("%s \n", recvBuff);


}
if(bytesReceived < 0)
{
printf("\n Read Error \n");
}
return 0;
}
Server:
HEMANT KUMAR | 1901530100014 | B.TECH CSE 3rd YEAR
#include <sys/socket.h>
#include <netinet/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>
int main(void)
{
int listenfd = 0;
int connfd = 0;
struct sockaddr_in serv_addr;
char sendBuff[1025];
int numrv;
listenfd = socket(AF_INET, SOCK_STREAM, 0);

printf("Socket retrieve success\n");


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));
if(listen(listenfd, 10) == -1)
{
printf("Failed to listen\n");
return -1;
}
while(1)
{
connfd = accept(listenfd, (struct sockaddr*)NULL ,NULL);
/* Open the file that we wish to transfer */

FILE *fp = fopen("sample_file.txt","rb");


if(fp==NULL)
{
printf("File opern error");
return 1;
}

HEMANT KUMAR | 1901530100014 | B.TECH CSE 3rd YEAR


/* Read data from file and send it */
while(1)
{
/* First read file in chunks of 256 bytes */
unsigned char buff[256]={0};
int nread = fread(buff,1,256,fp);
printf("Bytes read %d \n", nread);
/* If read was success, send data. */
if(nread > 0)
{
printf("Sending \n");
write(connfd, buff, nread);
}
if (nread < 256)
{
if (feof(fp))
printf("End of file\n");
if (ferror(fp))
printf("Error reading\n");
break;
}
}
close(connfd);
sleep(1);

}
return 0;
}

HEMANT KUMAR | 1901530100014 | B.TECH CSE 3rd YEAR


PROGRAM: 10

Aim: Applications using TCP and UDP Sockets like


d. DNS
IMPLEMENTATION OF SIMPLE DNS

AIM: To write a UDP program for implementing the simple DNS service.

ALGORITHM:

UDP Echo Server

1. Include necessary header files to support functions for Socket definitions,Socket


types,Internet addresses,I/O functions,UNIX system calls.
2. Declare variables for Socket ID,Port number,Socket addresses,Character buffer etc.
3. Create socket for server .
4. Bind socket with addresses.
5. Specify number of allowed connections.
6. Retrieve information from Connected Socket.
7. Echo retrieved information to Connected Socket.
8. Close Connected Socket

UDP Echo Client

1. Include necessary header files to support functions for Socket definitions,Socket


types,Internet addresses,I/O functions,UNIX system calls.
2. Declare variables for Socket ID,Port number,Socket addresses,Character buffer etc.
3. Create socket for client.
4. Connect client socket to the server socket addresses.
5. Give message to be echoed.
6. Retrieve echoed information from server and display it.
7. Close the Socket.

SERVER PROGRAM
import java.net.*;
import java.io.*;
class p1sender {
public static void main(String args[]) throws Exception {
byte senderBuffer[] = new byte[128]; // Packets 128 bytes long
String toName, userIn;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
DatagramSocket senderSocket = new DatagramSocket(999);
// Create socket for sending
if (args.length > 0) toName = args[0]; // IP or DNS from command line
else toName = "localhost";
while ((userIn=in.readLine())!=null ){ // Read standard input
senderBuffer=userIn.getBytes(); // Convert from string to byte array
// Send datagram packet out socket

HEMANT KUMAR | 1901530100014 | B.TECH CSE 3rd YEAR


senderSocket.send(new DatagramPacket( senderBuffer, senderBuffer.length,

InetAddress.getByName(toName), 666));
}
}
}

CLIENT PROGRAM
import java.net.*;
class p1receiver {
public static void main(String args[]) throws Exception {
byte receiveData[] = new byte[128];
DatagramSocket receiveSocket = new DatagramSocket(666); // Create socket for receiving
DatagramPacket receivePacket = new DatagramPacket(receiveData, 128);
while (true) {
receiveSocket.receive(receivePacket); // Wait for datagram packet to arrive
// Print packet contents as String
System.out.println(new String(receivePacket.getData(), 0, receivePacket.getLength()));
}
}}

OUTPUT:

SERVER

CLIENT

HEMANT KUMAR | 1901530100014 | B.TECH CSE 3rd YEAR


RESULT:
Thus the program was executed and output is verified successfully.

HEMANT KUMAR | 1901530100014 | B.TECH CSE 3rd YEAR

You might also like