Está en la página 1de 58

18CSC302J – Computer Networks LAB

SEMESTER – V

ACADEMIC YEAR: 2020-2021

NAME : Naren V
REG NO : RA1811003040173

Department of Computer Science and Engineering


SRM INSTITUTE OF SCIENCE AND
TECHNOLOGY
(UNDER SECTION 3 OF THE UGC ACT, 1956)
VADAPALANI CAMPUS
VADAPALANI, CHENNAI-600 026.

1
BONAFIDE CERTIFICATE

This is to certify that the bonafide record work done by


Name____Naren V_____Reg no. _RA1811003040173___of B.Tech
degree in the Computer Networks Laboratory in SRM Institute of
Science and Technology,Vadapalani campus, Chennai during the
academic year 2020-2021.

Lab in charge Head of the Department

Submitted for University Examination held on 7th December 2020 at

SRM INSTITUTE OF SCIENCE AND TECHNOLOGY,

Vadapalani.

2
Internal Examiner- I Internal
Examiner- II
LIST OF EXPERIMENTS

Ex.No Name of the Page Date Marks Signature


. Exercise No. of the
Faculty
1. Study of header 5 07.08.202
files with respect to 0
socket
programming
2. Study of Basic 8 14.08.202
Functions of Socket 0
Programming
3. Simple TCP/IP 17 21.08.202
Client Server 0
Communication
4. UDP Echo Client 20 04.09.202
Server 0
Communication
5. Concurrent TCP/IP 23 18.09.202
Day-Time Server 0
6. Half Duplex Chat 26 25.09.202
Using TCP/IP 0
7. Full Duplex Chat 30 09.10.202
Using TCP/IP 0
8. Implementation of 40 16.10.202
File Transfer 0
Protocol
9. Remote Command 43 30.10.202
Execution Using 0
UDP
10. ARP 46 06.11.202
Implementation 0
Using FTP
3
11. Implementation of 51 13.11.202
NAT 0
12. Communication 53 20.11.202
using HDLC 0
13. Communication 55 27.11.202
using PPP 0

Exp.No: 01
Date: 07.08.2020

Study of header files with respect to socket


programming
4
AIM:
To discuss some of the header files used for socket
programming

Description of header files:

1. stdio.h:
Has standard input and output library providing simple and efficient
buffered stream IO interface.

2. unistd.h:
It is a POSIX standard for open system interface. [Portable
Operating System Interface]

3. string.h:
        This header file is used to perform string manipulation operations on
NULL terminated strings.(Bzero -0 the m/y)

4. stdlib.h:
        This header file contains the utility functions such as string
conversion routines, memory allocation routines, random number
generator, etc.  

5. sys/types.h:
Defines the data type of socket address structure in unsigned long.

6. sys/socket.h:
        The socket functions can be defined as taking pointers to the generic
socket address structure called sockaddr. 

7. netinet/in.h:
Defines the IPv4 socket address structure commonly called Internet
socket address structure called sockaddr_in.

8. netdb.h:

5
        Defines the structure hostent for using the system call  gethostbyname
to get the network host entry.

9. time.h:
Has structures and functions to get the system date and time and to
perform time manipulation functions. We use  the function ctime(),
that is defined in this header file , to calculate the current date and
time.

10. sys/stat.h:
Contains the structure stat to test a descriptor to see if it is of a
specified type. Also it is used to display file or file system status.stat()
updates any time related fields.when copying from 1 file to another.

11. sys/ioctl.h:
Macros and defines used in specifying an ioctl request are located in
this header file. We use the function ioctl() that is defined in this
header file. ioctl() function is used to perform ARP cache operations.

12. pcap.h:
Has function definitions that are required for packet capturing. Some
of the functions are pcap_lookupdev(),pcap_open_live() and
pcap_loop(). pcap_lookupdev() is used to initialize the network
device.The device to be sniffed is opened using the pcap_open_live().
Pcap_loop() determines the number of packets to be sniffed.

13. net/if_arp.h:
Contains the definitions for Address Resolution Protocol. We use
this to manipulate the ARP request structure and its data members
arp_pa,arp_dev and arp_ha. The arp_ha structure’s data member
sa_data[ ] has the hardware address.

14. errno.h:
       It sets an error number when an error and that error can be
displayed using perror function. It has symbolic error names. The
error number is never set to zero by any library function.

6
15. arpa/inet.h:
       This is used to convert internet addresses between ASCII
strings and network byte ordered binary values (values that are
stored in socket address structures). It is used for inet_aton,
inet_addr, inet_ntoa functions.

RESULT: The basic header files used for Socket Programming was
studied successfully.

Exp.No: 02
Date: 14.08.2020

Study of Basic Functions of Socket Programming


7
AIM: To discuss some of the basic functions used for socket
programming.

Description of basic functions:

1.man socket

NAME:

           Socket – create an endpoint for communication.

SYNOPSIS:

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

DESCRIPTION:

 Socket creates an endpoint for communication and returns


a descriptor.
 The domain parameter specifies a common domain this
selects the protocol family which will be used for
communication.
 These families are defined in <sys/socket.h>.

FORMAT:

NAME PURPOSE
PF_UNIX,PF_LOCA Local Communication.
L
PF_INET IPV4 Internet Protocols.
PF_IPX IPX-Novell  Protocols.
PF_APPLETALK Apple Talk.

8
 The socket has the indicated type, which specifies the
communication semantics.

TYPES:

1.SOCK_STREAM:

 Provides sequenced , reliable, two-way , connection based


byte streams.
 An out-of-band data transmission mechanism, may be
supported.
2.SOCK_DGRAM:
 Supports datagram (connectionless, unreliable messages
of a fixed maximum length).
3.SOCK_SEQPACKET:
 Provides a sequenced , reliable, two-way connection
based data transmission path for datagrams of fixed
maximum length.
4.SOCK_RAW:
 Provides raw network protocol  access.
5.SOCK_RDM:
 Provides a reliable datagram layer that doesn’t guarantee
ordering.
6.SOCK_PACKET:
 Obsolete and shouldn’t be used in new programs.

2.man connect:

NAME:
           connect – initiate a connection on a socket.

SYNOPSIS:
            #include<sys/types.h>
            #include<sys/socket.h>

9
            int connect(int sockfd,const (struct
sockaddr*)serv_addr,socklen_t addrlen);

DESCRIPTION:

 The file descriptor sockfd must refer to a socket.


 If the socket is of type SOCK_DGRAM then the
serv_addr address is the address to which datagrams are
sent by default and the only addr from which datagrams
are received.
 If the socket is of type SOCK_STREAM or
SOCK_SEQPACKET , this call attempts to make a
connection to another socket.

RETURN VALUE:

 If the connection or binding succeeds, zero is returned.


 On error , -1 is returned , and error number is set
appropriately.

ERRORS:

EBADF Not a valid Index.


EFAULT The socket structure address is outside the
user’s  address space.
ENOTSOCK Not associated with a socket.
EISCONN Socket is already connected. 
ECONNREFUSE No one listening on the remote address.
D

3.man accept

NAME:

     accept/reject job is sent to a destination.


SYNOPSIS:

10
      accept destination(s)
      reject[-t] [-h server] [-r reason] destination(s)

DESCRIPTION:

 accept instructs the printing system to accept print jobs to


the specified destination.
 The –r option sets the reason for rejecting print jobs.
 The –e option forces encryption when connecting to the
server.

4.man send

NAME:

        send, sendto, sendmsg   - send a message from a socket.

SYNOPSIS:

     #include<sys/types.h>
     #include<sys/socket.h>

ssize_t send(int s, const void *buf, size_t len, int flags);


ssize_t sendto(int s, const void *buf, size_t len, int flags, const struct
sock_addr*to, socklen_t tolen);
ssize_t sendmsg(int s, const struct msghdr *msg, int flags);

DESCRIPTION:

 The system calls send, sendto and sendmsg are used to


transmit a message to another socket.
 The send call may be used only when the socket is in a
connected state.
 The only difference between send and write is the
presence of flags.
11
 The parameter is the file descriptor of the sending socket.

5.man recv

NAME:

            recv, recvfrom, recvmsg – receive a message from a socket.

SYNOPSIS:

              #include<sys/types.h>
              #include<sys/socket.h>
ssize_t recv(int s, void *buf, size_t len, int flags);
ssize_t recvfrom(int s, void *buf, size_t len, int flags, struct sockaddr
*from, socklen_t* from len);
ssize_t recvmsg(int s, struct msghdr *msg, int flags);

DESCRIPTION:

 The recvfrom and recvmsg calls are used to receive


messages from a socket, and may be used to recv data on
a socket whether or not it is connection oriented.
 If from is not NULL, and the underlying protocol
provides the src addr , this src addr is filled in.
 The recv call is normally used only on a connection
socket and is identical to recvfrom with a NULL from
parameter.
6.man read

NAME:

  read, readonly, return

7.man write

NAME:

12
         write- send a message to another  user.

SYNOPSIS:

           write user[ttyname]

DESCRIPTION:

 write allows you to communicate with other users, by


copying lines from terminal to  ………
 When you run the write and the user you are writing to get
a message of the form:
            Message from yourname @yourhost on yourtty at
hh:mm:…
 Any further lines you enter  will be copied to the  specified
user’s terminal.
 If  the other user wants to reply  they must run write as well.

8. ifconfig

NAME:

       ifconfig-  configure a network interface.

SYNOPSIS:

        ifconfig[interface]
        ifconfig interface[aftype] options | address……

DESCRIPTION:

 ifconfig is used to configure the kernel resident network


interfaces.
 It is used at boot time to setup interfaces as necessary.
 After that, it is usually only needed when debugging or
when system tuning is needed.

13
 If no arguments are given, ifconfig displays the status of the
currently active interfaces.
9. man bind

SYNOPSIS:

          bind[-m keymap] [-lp sv psv]

10. man htons/ man htonl

NAME:

         htonl, htons, ntohl, ntohs -  convert values between host and


network byte order.

SYNOPSIS:

            #include<netinet/in.h>
              uint32_t    htonl(uint32_t hostlong); 
              uint16_t    htons(uint32_t hostshort); 
              uint32_t    ntohl(uint32_t netlong); 
              uint16_t    ntohs(uint16_t netshort); 

DESCRIPTION:

 The htonl() function converts the unsigned integer hostlong


from host byte order to network byte order.
 The htons() converts the unsigned short integer hostshort
from host byte order to network byte order.
 The ntohl() converts the unsigned integer netlong from 
network byte order to host byte order.

11. man gethostname

NAME:

         gethostname, sethostname- get/set host name.

14
SYNOPSIS:

            #include<unistd.h>
            int gethostname(char *name,size_t len);
            int sethostname(const char *name,size_t len);     

DESCRIPTION:

 These functions are used to access or to change the host


name of the current processor.
 The gethostname() returns a NULL terminated
hostname(set earlier by sethostname()) in the array name
that has a length of len bytes.
 In case the NULL terminated then hostname does not fit
,no error is returned, but the hostname  is truncated.
 It is unspecified whether the truncated hostname will be
NULL terminated.

12. man gethostbyname

NAME:

        gethostbyname, gethostbyaddr, sethostent, endhostent, herror,


hstr – error – get network host entry.

SYNOPSIS:

            #include<netdb.h>
               extern int h_errno;
               struct hostent *gethostbyname(const char *name);  
           #include<sys/socket.h>
               struct hostent *gethostbyaddr(const char *addr)int len, int
type);
               struct hostent *gethostbyname2(const char *name,int af);

DESCRIPTION:
15
 The gethostbyname() returns a structure of type hostent for
the given hostname.
 Name->hostname or IPV4/IPV6 with dot notation.
 gethostbyaddr()- struct of type hostent / host address length
 Address types- AF_INET, AF_INET6.
 sethostent() – stay open is true(1).
 TCP socket  connection should be open during queries.
 Server queries for UDP datagrams.
 endhostent()- ends the use of TCP connection.
 Members of hostent structure:
a. h_name
b. h_aliases
c. h_addrtype
d. h_length
e. h_addr-list
f. h_addr. 

RESULT:
The basic functions used for Socket Programming was studied
successfully.

16
Exp.No: 03
Date: 21.08.2020

Simple TCP/IP Client Server Communication

AIM:
To create a simple TCP/IP connection between server and client
using java code.

Server (Filename: chatserver.java)

import java.io.*; 
import java.net.*; 
public class chatserver
{

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

{
ServerSocket sersock=new ServerSocket(3000);
System.out.println("Server ready for chatting"); Socket
sock=sersock.accept();
BufferedReader KeyRead= new BufferedReader(new
InputStreamReader(System.in));
OutputStream ofstream=sock.getOutputStream(); PrintWriter
pwrite=new PrintWriter(ofstream,true); InputStream
istream=sock.getInputStream();
BufferedReader receivedread=new BufferedReader(new
InputStreamReader(istream)); String receivemessage,sendmessage;
while(true)
{

if((receivemessage= receivedread.readLine())!=null)

17
System.out.println(receivemessage);

} sendmessage=KeyRead.readLine(); 
pwrite.println(sendmessage); 
System.out.flush();
}

Client (Filename: chatclient)

import java.io.*; 
import java.net.*; 
public class chatclient
{

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

{
Socket sock=new Socket("localhost",3000);

BufferedReader KeyRead=new BufferedReader(new


InputStreamReader(System.in)); 
OutputStream ofstream=sock.getOutputStream();
PrintWriter pwrite=new PrintWriter(ofstream,true); 
InputStream istream=sock.getInputStream();
BufferedReader receivedread=new BufferedReader(new
InputStreamReader(istream)); System.out.println("client ready for
chatting");
String receivemessage,sendmessage;

while(true)

18
sendmessage=KeyRead.readLine(); 
pwrite.println(sendmessage); 
System.out.flush();
if((receivemessage=receivedread.readLine())!=null)

{ System.out.println(receivemessage);
}

OUTPUT:

RESULT:

19
Thus a simple TCP/IP connection between server and client was
created using java code.

Exp.No: 04
Date: 04.09.2020

UDP Echo Client Server Communication


AIM:
To create a UDP Echo connection between server and client
using java code.

Server: (Filename: UDPServer)

import java.io.*;
import java.net.*;

class UDPServer
   {
     public static void main(String arg[])throws Exception
{
byte[] receiveData= new byte[1024];
byte[] sendData= new byte[1024];
DatagramSocket serversocket=new DatagramSocket(8000);
DatagramPacket receivePacket=new
DatagramPacket(receiveData,receiveData.length);
serversocket.receive(receivePacket);
BufferedReader b=new BufferedReader( new
InputStreamReader(System.in));
  String s=b.readLine();
/*String sentence=new String(receivePacket.getData());
System.out.println("Received messege is: "+sentence.trim());
sentence=sentence.toUpperCase();
System.out.println("Converted messege is:
"+sentence.trim());*/
InetAddress ip=receivePacket.getAddress();
int port=receivePacket.getPort();

20
//sendData=sentence.getBytes();
  sendData=s.getBytes();
DatagramPacket sendPacket=new
DatagramPacket(sendData,sendData.length,ip,port);
serversocket.send(sendPacket);
        }
     }

Client: (Filename: UDPClient.java)

import java.io.*;
import java.net.*;
import java.util.*;

class UDPClient
  {
    public static void main(String arg[])throws Exception
     {
byte[] receiveData=new byte[1024];
byte[] sendData=new byte[1024];
DatagramSocket clientSocket=new DatagramSocket();
DatagramPacket receivePacket=new
DatagramPacket(receiveData,receiveData.length);
BufferedReader in=new BufferedReader(new
InputStreamReader(System.in));
String sentence=in.readLine();
sendData=sentence.getBytes();
InetAddress ip=InetAddress.getByName("localhost");
DatagramPacket sendPacket=new
DatagramPacket(sendData,sendData.length,ip,8000);
clientSocket.send(sendPacket);
clientSocket.receive(receivePacket);
sentence=new String(receivePacket.getData());
System.out.println("New Sentence is: "+sentence.trim());
      }
   }

21
OUTPUT:

RESULT:
Thus a UDP Echo connection between server and client was
created using java code.
22
Exp.No: 05
Date: 18.09.2020

Concurrent TCP/IP Day-Time Server


AIM:
To show the date and time by creating a concurrent TCP/IP
connection between server and client using java code.

Server: (Filename: tcpdateserver)


import java.net.*; 
import java.io.*; 
import java.util.*; 
class tcpdateserver
{
public static void main(String args[])
{
ServerSocket ss=null;
Socket cs;
PrintStream ps; 
BufferedReader dis; 
String inet;
try
{
ss=new ServerSocket(4444); 
System.out.println("press ctrl+c to quit");
while(true)
{
cs=ss.accept();
ps=new PrintStream(cs.getOutputStream()); 
Date d=new Date();
ps.println(d);
dis=new BufferedReader(new
InputStreamReader(cs.getInputStream()));
inet=dis.readLine();

23
System.out.println("client system IPaddress is:"+inet);
ps.close();
dis.close();
}}
catch(IOException e)
{
System.out.println("the ecxeption is"+e);
}}}

Client: (Filename: tcpdateclient)


import java.net.*; 
import java.io.*; 
class tcpdateclient
{
public static void main(String args[])
{
Socket soc; 
BufferedReader dis; 
String sdate; 
PrintStream ps;
try
{
InetAddress ia=InetAddress.getLocalHost();
if(args.length==0)
soc=new Socket(InetAddress.getLocalHost(),4444);
else
soc=new Socket(InetAddress.getByName(args[0]),4444);
dis=new BufferedReader(new
InputStreamReader(soc.getInputStream()));
sdate=dis.readLine();
System.out.println("the date and time on server is :"+sdate);
ps=new PrintStream(soc.getOutputStream());
ps.println(ia);
ps.close();
}
catch(IOException e)
{

24
System.out.println("the exception is"+e);}}}
OUTPUT:

RESULT:
Thus the date and time was displayed by creating a concurrent
TCP/IP connection between server and client using java code.

25
Exp.No: 06
Date: 25.09.2020

Half Duplex Chat Using TCP/IP


AIM:
To establish half duplex communication (transmit data in just
one direction at a time) using java code.

Server
import java.io.*;
import java.net.*;
import java.lang.*;
class server1
{
public static void main(String a[])throws IOException
{
ServerSocket ss=new ServerSocket(8000);
Socket s=ss.accept();
PrintStream dos=new PrintStream(s.getOutputStream());
DataInputStream in=new DataInputStream(System.in);
DataInputStream inn=new DataInputStream(s.getInputStream());
while(true)
{
System.out.print("Enter the msg to send: ");
String str=in.readLine();
dos.println(str);

26
if(str.equals("end"))
{
ss.close();
break;
}
String str1=inn.readLine();
System.out.println("Messege received: "+str1);
if(str1.equals("end"))
{
ss.close();
break;
}
}
}
}

Client
import java.io.*;
import java.net.*;
import java.lang.*;
class client1
{
public static void main(String a[])throws IOException
{
Socket s=new Socket("LocalHost",8000);
27
DataInputStream in=new DataInputStream(s.getInputStream());
DataInputStream inn=new DataInputStream(System.in);
PrintStream dos=new PrintStream(s.getOutputStream());
while(true)
{
String str=in.readLine();
System.out.print("Messege received:"+str);
if(str.equals("end"))
{
s.close();
break;
}
System.out.print("\nEnter the msg to send: ");
String str1=inn.readLine();
dos.println(str1);
if(str1.equals("end"))
{
s.close();
break;
}
}
}
}

28
OUTPUT:

RESULT:
Thus a half duplex communication (transmit data in just one
direction at a time) was established using java code

29
Exp.No: 07
Date: 09.10.2020

Full Duplex Chat Using TCP/IP


AIM:
To establish full duplex communication (transmit data in just
two directions at a time) using java code.

UserInput.java
import java.io.IOException;
public interface UserInput {
void write(String input) throws IOException;
}
Keyboard.java
import java.io.*;
public class Keyboard {
static BufferedReader buffer;
static {
InputStreamReader bis = new InputStreamReader(System.in);
buffer = new BufferedReader(bis);
}
public static String readline() throws IOException {
return buffer.readLine();

30
}
}
Client.java
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
public class Client extends Thread implements UserInput {
public void connect(int port) throws IOException {
InetSocketAddress address = new
InetSocketAddress(&quot;localhost&quot;, 9999);
channel = SocketChannel.open(address);
channel.configureBlocking(false);
selector = Selector.open();
channel.register(selector, SelectionKey.OP_READ);
}

@Override
public void run() {
Iterator&lt;SelectionKey&gt; it;
31
while (channel.isConnected()) {
try {
if (selector.select() != 0) {
it = selector.selectedKeys().iterator();
while (it.hasNext()) {
SelectionKey key = it.next();
handleKey(key);
it.remove();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void handleKey(SelectionKey key) throws IOException {
if (key.isReadable()) {
ByteBuffer buffer = ByteBuffer.allocate(80);
buffer.clear();
channel.read(buffer);
if (buffer.get(0) == 0) {
return;

32
}
System.out.printf(&quot;Server says: %s&quot;, new
String(buffer.array()));
}
}
@Override
public void write(String input) throws IOException {
channel.write(ByteBuffer.wrap(input.getBytes()));
}
SocketChannel channel;
Selector selector;
}
Server.java

import java.io.IOException;
import java.net.Inet4Address;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
33
import java.util.Iterator;
import java.util.List;
public class Server extends Thread implements UserInput {
public void listen(int port) throws IOException {
channel = ServerSocketChannel.open();
channel.configureBlocking(false);
channel.socket().bind(new InetSocketAddress(9999));
selector = Selector.open();
channel.register(selector, SelectionKey.OP_ACCEPT);
}
@Override
public void run() {
clients = new ArrayList&lt;SocketChannel&gt;();
Iterator&lt;SelectionKey&gt; it;
while (channel.isOpen()) {
try {
if (selector.select() != 0) {
it = selector.selectedKeys().iterator();
while (it.hasNext()) {
SelectionKey key = it.next();
handleKey(key);
it.remove();

34
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void handleKey(SelectionKey key) throws IOException {
// System.out.println(&quot;Server.handleKey&quot;);

if (key.isAcceptable()) {
SocketChannel channelClient = channel.accept();
channelClient.configureBlocking(false);
channelClient.register(selector, SelectionKey.OP_READ |
SelectionKey.OP_WRITE);
System.out.println(&quot;Client is accepted&quot;);
clients.add(channelClient);
} else if (key.isReadable()) {
SocketChannel channelClient = (SocketChannel) key.channel();
if (!channelClient.isOpen()) {
System.out.println(&quot;Channel terminated by client&quot;);
}
ByteBuffer buffer = ByteBuffer.allocate(80);
35
buffer.clear();
channelClient.read(buffer);
if (buffer.get(0) == 0) {
System.out.println(&quot;Nothing to read.&quot;);
channelClient.close();
clients.remove(channelClient);
return;
}
System.out.printf(&quot;Client says: %s&quot;, new
String(buffer.array()));
} else if (key.isWritable()) {
}
}
List&lt;SocketChannel&gt; clients;
ServerSocketChannel channel;
Selector selector;
@Override
public void write(String input) throws IOException {
for(SocketChannel channelClient:clients) {
channelClient.write(ByteBuffer.wrap(input.getBytes()));
}
}
}
36
App.java

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class App {
public static void main(String[] args) throws InterruptedException,
IOException {
if (args.length == 0) return;
Thread worker;
final UserInput input;
if (&quot;host&quot;.equals(args[0])) {
System.out.println(&quot;Starting server app...&quot;);
Server server = new Server();
server.listen(9999);
worker = server;
input = server;
} else if (&quot;client&quot;.equals(args[0])) {
System.out.println(&quot;Starting client app...&quot;);
Client client = new Client();
client.connect(9999);
worker = client;
input = client;
37
} else {
System.exit(1);
return;
}
worker.start();
service.execute(new Runnable() {
@Override
public void run() {
System.out.println(&quot;Consuming user input..&quot;);
String line;
while (true) {
try {
line = Keyboard.readline();
input.write(line);
//System.out.println(&quot;Echo: &quot; + line);
} catch (IOException e) {

System.err.println(&quot;Could not write&quot;);


}
}
}
});

38
worker.join();
}
static ExecutorService service =
Executors.newSingleThreadExecutor();}
OUTPUT:

RESULT:
Thus a full duplex communication (transmit data in just two
directions at a time) was established using java code.
39
Exp.No: 08
Date: 16.10.2020

Implementation of File Transfer Protocol

AIM:
To transfer files from one host to another by implementing FTP.

Server:
import java.io.*;
import java.net.*;

class FTP_Server
{
public static void main(String[] args) throws Exception
{
ServerSocket s=new ServerSocket(6777);
Socket sr=s.accept();
FileInputStream fr=new FileInputStream("D:\\ftp_example.txt");
byte b[]=new byte[2002];
fr.read(b, 0, b.length);
OutputStream os=sr.getOutputStream();
os.write(b, 0, b.length);
}
}

40
Client
import java.io.*;
import java.net.*;

class FTP_Client
{
public static void main(String[] args) throws Exception
{
byte []b=new byte[2002];
Socket sr=new Socket("localhost", 6777);
InputStream is=sr.getInputStream();
FileOutputStream fr=new FileOutputStream("E:\\ftp_example.txt");
is.read(b, 0, b.length);
fr.write(b, 0, b.length);
}
}

OUTPUT:
41
RESULT:
Thus files were transfered from one host to another by
implementing FTP.

42
Exp.No: 09
Date: 30.10.2020

Remote Command Execution Using UDP

AIM:
To execute remote commands using UDP.
Server:

import java.io.*;
import java.net.*;

class RemoteServer11
{
public static void main(String args[])
{
byte[] receiveData = new byte[1024];
byte[] sendData  = new byte[1024];
try
{
while(true)
{
DatagramSocket serverSocket = new DatagramSocket(9876);

DatagramPacket receivePacket = new DatagramPacket(receiveData,


receiveData.length);

serverSocket.receive(receivePacket);

String cmd = new String(receivePacket.getData());

InetAddress IPAddress = receivePacket.getAddress();


int port = receivePacket.getPort();
Runtime H=Runtime.getRuntime();
Process P=H.exec(cmd);
43
System.out.println(" The " + cmd + " Command is Executed
Successfully. ");
serverSocket.close();
}
}
catch(Exception e)
{
System.out.println(" Error : " + e.getMessage());
}
}
}

Client: 
import java.io.*;
import java.net.*;

class RemoteClient11
{
public static void main(String args[])throws IOException
{
BufferedReader inFromUser =
        new BufferedReader(new InputStreamReader(System.in));

      DatagramSocket clientSocket = new DatagramSocket();

InetAddress IPAddress = InetAddress.getLocalHost();

      byte[] sendData = new byte[1024];


      byte[] receiveData = new byte[1024];
      System.out.println("Enter the command:");

      String sentence = inFromUser.readLine();

      sendData = sentence.getBytes();
   DatagramPacket sendPacket = new DatagramPacket(sendData,
sendData.length,IPAddress, 9876);

44
      clientSocket.send(sendPacket);

      //DatagramPacket receivePacket =new


DatagramPacket(receiveData, receiveData.length);

      //clientSocket.receive(receivePacket);

      //String modifiedSentence = new String(receivePacket.getData());

      //System.out.println("FROM SERVER:" + modifiedSentence);


      //Thread.sleep(1000);   

      clientSocket.close();
      inFromUser.close();

    }
}
OUTPUT:

RESULT:
Thus remote commands were executed using UDP.

45
Exp.No: 10
Date: 06.11.2020

ARP Implementation Using FTP

AIM:
To implement ARP using FTP.

This program automatically creates a file with the IP address of


machines, their MAC address and type. 

ARP protocol is simulated by reading an IP address and returning the


MAC address. 
RARP protocol is simulated by reading an MAC address and
returning the IP address 

The program can be extended to read an IP Address/Mac Address and


a message and send a packet to the specified machine using TCP/IP or
Datagram sockets

ARP table
After obtaining a host's MAC address, the switch adds the IP-to-MAC
mapping to its own ARP table. This mapping is used for forwarding
packets with the same destination in future.

An ARP table contains either category of ARP entries: dynamic or


static.

Dynamic ARP entry


A dynamic entry is automatically created and maintained by ARP. It
can age out, be updated by a new ARP packet, or be overwritten by a
static ARP entry. A dynamic ARP entry is removed when its age
timer expires or the interface goes down.

Static ARP entry


46
A static ARP entry is manually configured and maintained. It does not
age out or cannot be overwritten by a dynamic ARP entry.

import java.io.*;
import java.util.*;

public class arp_rarp


{
     private static final String Command = "arp -a";
    
     public static void getARPTable(String cmd) throws Exception
     {  
          File fp = new File("ARPTable.txt");
          FileWriter fw = new FileWriter(fp);

          BufferedWriter bw = new BufferedWriter(fw);


         
          Process P = Runtime.getRuntime().exec(cmd);
          Scanner S = new
Scanner(P.getInputStream()).useDelimiter("\\A");
          
          while(S.hasNext())
              bw.write(S.next());

          bw.close();
          fw.close();
     }
    

     public static void findMAC(String ip) throws Exception


     {
          File fp = new File("ARPTable.txt");
          FileReader fr = new FileReader(fp);
          BufferedReader br = new BufferedReader(fr);
         
          String line;
         

47
          while ((line = br.readLine()) != null)
          {
               if (line.contains(ip))
              {
                   System.out.println("Internet Address      Physical Address 
Type");
                   System.out.println(line);
                   break;
              }
          }
          if((line == null))
              System.out.println("Not found");
         
          fr.close(); 
          br.close();        
     }  
    
  
     public static void findIP(String mac) throws Exception
     {
          File fp = new File("ARPTable.txt");
          FileReader fr = new FileReader(fp);
          BufferedReader br = new BufferedReader(fr);
         
          String line;
         
          while ((line = br.readLine()) != null)
          {
              if (line.contains(mac))
              {
                   System.out.println("Internet Address      Physical Address 
Type");
                   System.out.println(line);
                   break;
              }
          }
         

48
          if((line == null))
              System.out.println("Not found");
         
          fr.close(); 
          br.close();        
     }
    

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


     {
          getARPTable(Command);

          Scanner S = new Scanner(System.in);

          System.out.println("ARP Protocol.");
          System.out.print("Enter IP Address: ");
          String IP = S.nextLine();
          findMAC(IP);

          System.out.println("RARP Protocol.");
          System.out.print("Enter MAC Address: ");
          String MAC = S.nextLine();
          findIP(MAC);
     }
}

49
OUTPUT:
Type ipconfig in cmd to check the ip address of your system

RESULT:

50
Thus ARP was implemented using FTP.

Exp.No: 11
Date: 13.11.2020
Implementation of NAT
AIM:
To implement NAT using cisco packet tracer.
PROCEDURE:

 Assemble PCs, Switches and Routers.


 Give connections and name those PCs, Routers and Gateways.
 Set IP configuration for PCs.
 Configure Router using CLI in R0 and R1.
 Check Ping using Command terminal.
 Using access-list and nat inside overload command PAT is
achieved.
 Using nat inside static command Static NAT is achieved.

OUTPUT:
NAT Overload or PAT:

51
52
STATIC NAT

RESULT: Thus NAT was implemented using cisco packet tracer.

Exp.No: 12
Date: 20.11.2020
Communication using HDLC
AIM:
To establish communication using HDLC in cisco packet tracer.
PROCEDURE:

 Assemble PCs, Switches and Routers.

53
 Give connections and name those PCs, Routers and Gateways.
 Set IP configuration for PCs.
 Configure Router using CLI in R0 and R1.
 Check Ping using Command terminal.
 Using sh int s2/0 check for hdlc enabling.
 If not enabled , enable hdlc.
OUTPUT:

54
RESULT:

55
Thus communication was established using HDLC in cisco
packet tracer.
Exp.No: 13
Date: 27.11.2020
Communication using PPP
AIM:
To establish communication using PPP in cisco packet tracer.
PROCEDURE:

 Assemble PCs, Switches and Routers.


 Give connections and name those PCs, Routers and
Gateways.
 Set IP configuration for PCs.
 Configure Router using CLI in R0 and R1.
 Check Ping using Command terminal.
 Enable ppp and check for encapsulation of ppp.
 Enable password protection for Router1 and Router2 using
pap.

OUTPUT:

56
57
RESULT: Thus communication was established using PPP in cisco
packet tracer.

58

También podría gustarte