BE-CSE-IT Network Lab Manual
BE-CSE-IT Network Lab Manual
BE-CSE-IT Network Lab Manual
LAB MANUAL
12 Implementation of CRC
Date:
Theory
Inet Address
getLocalHost()
Returns the address of the local host. This is achieved by retrieving the name of the host from the
system, then resolving that name into an InetAddress.
Note: The resolved address may be cached for a short period of time.
If there is a security manager, its checkConnect method is called with the local host name and -1
as its arguments to see if the operation is allowed. If the operation is not allowed, an InetAddress
representing the loopback address is returned.
Returns:
the address of the local host.
Throws:
UnknownHostException - if the local host name could not be resolved into an address.
SOURCE CODE:
import java.util.*;
import java.lang.*;
import java.net.*;
try
InetAddress IPO=InetAddress.getLocalHost();
catch(Exception e)
System.out.println("Exception caught="+e.getMessage());
SAMPLE INPUT/OUTPUT:
E:\EX1>javac getOwnIP.java
E:\EX1>java getOwnIP
IP of this system=10.1.60.11
Ex. No. 1.b
Date:
Theory
1. getByName
The host name can either be a machine name, such as "java.sun.com", or a textual
representation of its IP address. If a literal IP address is supplied, only the validity of the address
format is checked.
For host specified in literal IPv6 address, either the form defined in RFC 2732 or the
literal IPv6 address format defined in RFC 2373 is accepted. IPv6 scoped addresses are also
supported. See here for a description of IPv6 scoped addresses.
Parameters:
host - the specified host, or null.
Returns:
an IP address for the given host name.
Throws:
UnknownHostException - if no IP address for the host could be found, or if a scope_id was
specified for a global IPv6 address.
SecurityException - if a security manager exists and its checkConnect method doesn't allow
the operation
SOURCE CODE:
import java.util.*;
import java.lang.*;
import java.net.*;
try
InetAddress IPO=InetAddress.getByName(args[0]);
catch(Exception e)
SAMPLE INPUT/OUTPUT:
E:\EX1>javac getRemoteIP.java
E:\EX1>java getRemoteIP
Date:
Theory
Socket
Normally, a server runs on a specific computer and has a socket that is bound to a specific port
number. The server just waits, listening to the socket for a client to make a connection request.
On the client-side: The client knows the hostname of the machine on which the server is running
and the port number on which the server is listening. To make a connection request, the client
tries to rendezvous with the server on the server's machine and port. The client also needs to
identify itself to the server so it binds to a local port number that it will use during this
connection. This is usually assigned by the system.
If everything goes well, the server accepts the connection. Upon acceptance, the server gets a
new socket bound to the same local port and also has its remote endpoint set to the address and
port of the client. It needs a new socket so that it can continue to listen to the original socket for
connection requests while tending to the needs of the connected client.
On the client side, if the connection is accepted, a socket is successfully created and the client
can use the socket to communicate with the server.
The client and server can now communicate by writing to or reading from their sockets.
Definition:
A socket is one endpoint of a two-way communication link between two programs running on
the network. A socket is bound to a port number so that the TCP layer can identify the
application that data is destined to be sent to.
The java.net package in the Java platform provides a class, Socket, that implements one
side of a two-way connection between your Java program and another program on the network.
The Socket class sits on top of a platform-dependent implementation, hiding the details of any
particular system from your Java program. By using the java.net.Socket class instead of relying
on native code, your Java programs can communicate over the network in a platform-
independent fashion.
Additionally, java.net includes the ServerSocket class, which implements a socket that
servers can use to listen for and accept connections to clients. This lesson shows you how to use
the Socket and ServerSocket classes.
Socket constructor
Creates a stream socket and connects it to the specified port number at the specified IP address.
If the application has specified a socket factory, that factory's createSocketImpl method is
called to create the actual socket implementation. Otherwise a "plain" socket is created.
If there is a security manager, its checkConnect method is called with the host address
and port as its arguments. This could result in a SecurityException.
Parameters:
address - the IP address.
port - the port number.
Any thread currently blocked in an I/O operation upon this socket will throw a SocketException.
Once a socket has been closed, it is not available for further networking use (i.e. can't
be reconnected or rebound). A new socket needs to be created.
Closing this socket will also close the socket's InputStream and OutputStream.
SOURCE CODE:
import java.net.*;
import java.io.*;
int startPortRange = 0;
int stopPortRange = 0;
int n=1;
startPortRange = Integer.parseInt(args[0]);
stopPortRange = Integer.parseInt(args[1]);
try
Serversok.close();
n=0;
catch(Exception e)
{}
if(n!=0)
n=1;
SAMPLE INPUT/OUTPUT:
E:\EX2>javac PortScanner.java
Date:
Theory
Socket
Sockets provide the communication mechanism between two computers using TCP. A client
program creates a socket on its end of the communication and attempts to connect that socket to
a server.
When the connection is made, the server creates a socket object on its end of the communication.
The client and server can now communicate by writing to and reading from the socket.
Class Writer
public abstract class Writer extends Object implements Appendable, Closeable, Flushable
Abstract class for writing to character streams. The only methods that a subclass must
implement are write(char[], int, int), flush(), and close(). Most subclasses, however, will override
some of the methods defined here in order to provide higher efficiency, additional functionality,
or both.
Methods
InputStream getInputStream()
Returns an input stream for this socket.
OutputStream getOutputStream()
Returns an output stream for this socket.
void close()
Closes this socket.
SOURCE CODE FOR CLIENT:
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.Socket;
String hostname="localhost";
Socket connection=null;
connection=new Socket(hostname,DEFAULT_PORT);
out.write("\r\n");
InputStream raw=connection.getInputStream();
int c;
while((c=in.read())!=-1)
{
if((c>=32 && c<127)||c=='\t'||c=='\r'||c=='\n')
System.out.write(c);
connection.close();
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.util.Iterator;
import java.util.Set;
boolean eof=false;
while(!eof)
String line=buff.readLine();
if(line==null)
eof=true;
else
pw.println(line);
buff.close();
ServerSocketChannel sockChannel=ServerSocketChannel.open();
sockChannel.configureBlocking(false);
InetSocketAddress server=new InetSocketAddress("localhost",79);
ServerSocket socket=sockChannel.socket();
socket.bind(server);
Selector selector=Selector.open();
sockChannel.register(selector,SelectionKey.OP_ACCEPT);
while(true)
selector.select();
Set keys=selector.selectedKeys();
Iterator it=keys.iterator();
while(it.hasNext())
SelectionKey selKey=(SelectionKey)it.next();
it.remove();
if(selKey.isAcceptable())
ServerSocketChannel selChannel=(ServerSocketChannel)selKey.channel();
ServerSocket selSocket=selChannel.socket();
Socket connection=selSocket.accept();
pw.flush();
String outLine=null;
String inLine=is.readLine();
if(inLine.length()>0)
outLine=inLine;
readPlan(outLine, pw);
pw.flush();
pw.close();
is.close();
connection.close();
SAMPLE INPUT/OUTPUT:
E:\EX3>javac New.java
E:\EX3>java New
E:\EX3>javac Main.java
E:\EX3>java Main
Date:
Theory
Inetaddress
getByName
The host name can either be a machine name, such as "java.sun.com", or a textual representation
of its IP address. If a literal IP address is supplied, only the validity of the address format is
checked.
Parameters:
host - the specified host, or null.
Returns:
an IP address for the given host name.
isReachable
The network interface and ttl parameters let the caller specify which network interface
the test will go through and the maximum number of hops the packets should go through. A
negative value for the ttl will result in an IllegalArgumentException being thrown.
The timeout value, in milliseconds, indicates the maximum amount of time the try
should take. If the operation times out before getting an answer, the host is deemed
unreachable. A negative value will result in an IllegalArgumentException being thrown.
Parameters:
netif - the NetworkInterface through which the test will be done, or null for any
interface ttl - the maximum numbers of hops to try or 0 for the default
timeout - the time, in milliseconds, before the call aborts
Returns:
a Boolean indicating if the address is reachable.
SOURCE CODE:
import java.net.*;
import java.io.*;
System.out.println("Pinging status");
String ipa="GFL-335";
try
InetAddress IPA=InetAddress.getByName("Gfl-335");
boolean status=IPA.isReachable(50000);
if(status)
else
catch(IOException e)
SAMPLE INPUT/OUTPUT:
E:\EX4>javac Ping.java
E:\EX4>java Ping
Pinging status
Date:
To implement the peer to peer communication through UDP using java program
Theory
UDP
UDP Datagram
UDP network traffic is organized in the form of datagrams . A datagram comprises one
message unit. The first eight (8) bytes of a datagram contain header information and the
remaining bytes contain message data.
A UDP datagram header consists of four (4) fields of two bytes each:
UDP port numbers allow different applications to maintain their own channels for data
similar to TCP. UDP port headers are two bytes long; therefore, valid UDP port numbers range
from 0 to 65535.
The UDP datagram size is a count of the total number of bytes contained in header and data
sections. As the header length is a fixed size, this field effectively tracks the length of the
variable-sized data portion (sometimes called payload). The size of datagrams varies depending
on the operating environment but has a maximum of 65535 bytes.
UDP checksums protect message data from tampering. The checksum value represents an
encoding of the datagram data calculated first by the sender and later by the receiver. Should an
individual datagram be tampered with or get corrupted during transmission, the UDP protocol
detects a checksum calculation mismatch. In UDP, checksumming is optional as opposed to TCP
where checksums are mandatory.
Datagram Socket
A datagram socket is the sending or receiving point for a packet delivery service. Each
packet sent or received on a datagram socket is individually addressed and routed. Multiple
packets sent from one machine to another may be routed differently, and may arrive in any order.
BufferedReader class
The BufferedReader class is used for fast reading operations of texts from a character-
input stream. It can be used to read single characters, arrays, and lines of data. The size of buffer
may or may not be specified. The readLine() method of the BufferedReader class can be used to
get the next line of characters from a file, and the skip(long n) method can be used to skip n
number of characters.
java.net.*;
class UDPClient
=sentence.getBytes();
clisock.send(sendpack);
clisock.receive(recpack);
clisock.close();
java.net.*;
class UDPServer
while(true)
{
DatagramPacket recpack=new DatagramPacket(receivedata,receivedata.length);
sersock.receive(recpack);
IPA=recpack.getAddress();
int port=recpack.getPort();
String csentence=sentence.toUpperCase();
senddata =csentence.getBytes();
sersock.send(sendpack);
SAMPLE INPUT/OUTPUT:
E:\EX5>javac UDPServer.java
E:\EX5>java UDPServer
Received : Hi Server
E:\EX5>javac UDPClient.java
E:\EX5>java UDPClient Hi
Server
Date:
Implementation of socket program for UDP Echo Client and Echo Server
Aim
To implement a socket program for UDP Echo Client and Echo Server using java
program
Theory
DatagramSocket
A datagram socket is the sending or receiving point for a packet delivery service. Each
packet sent or received on a datagram socket is individually addressed and routed. Multiple
packets sent from one machine to another may be routed differently, and may arrive in any order.
BufferedReader class
The BufferedReader class is used for fast reading operations of texts from a character-
input stream. It can be used to read single characters, arrays, and lines of data. The size of buffer
may or may not be specified. The readLine() method of the BufferedReader class can be used to
get the next line of characters from a file, and the skip(long n) method can be used to skip n
number of characters.
SOURCE CODE FOR CLIENT:
import java.net.*;
import java.io.*;
import java.lang.*;
public class EC
buff=s.getBytes();
InetAddress a=InetAddress.getByName("Gfl-335");
soc.send(pac);
System.out.println("End of sending");
buff1=s.getBytes();
pac=new DatagramPacket(buff1,buff1.length);
soc.receive(pac);
System.out.println(msg);
System.out.println("End of programming");
import java.net.*;
import java.io.*;
import java.lang.*;
public class ES
System.out.println("server started");
soc.receive(pac);
System.out.println(msg);
System.out.println("End of reception");
String s="From Server-Hello client"; byte[]
port=pac.getPort();
pac=new DatagramPacket(buff,buff1.length,a,port);
soc.send(pac);
System.out.println("End of sending");
SAMPLE INPUT/OUTPUT:
E:\EX6>javac ES.java
E:\EX6>java ES server
started
sending
E:\EX6>javac EC.java
E:\EX6>java EC
End of sending
of programming
Ex. No. 7.
Date:
Theory
DatagramSocket
A datagram socket is the sending or receiving point for a packet delivery service. Each
packet sent or received on a datagram socket is individually addressed and routed. Multiple
packets sent from one machine to another may be routed differently, and may arrive in any order.
BufferedReader class
The BufferedReader class is used for fast reading operations of texts from a character-
input stream. It can be used to read single characters, arrays, and lines of data. The size of buffer
may or may not be specified. The readLine() method of the BufferedReader class can be used to
get the next line of characters from a file, and the skip(long n) method can be used to skip n
number of characters.
TCP
TCP is one of the main protocols in TCP/IP networks. Whereas the IP protocol deals only
with packets, TCP enables two hosts to establish a connection and exchange streams of data.
TCP guarantees delivery of data and also guarantees that packets will be delivered in the same
order in which they were sent.
SOURCE CODE FOR CLIENT:
import java.lang.*;
import java.net.*;
import java.io.*;
class CliTCP
try
System.out.println("Received string:");
while(!in.ready())
System.out.println(in.readLine());
System.out.println("\n");
in.close();
catch(Exception e)
import java.lang.*;
import java.net.*;
import java.io.*;
class SerTCP
String data="Welcome";
try
Socket skt=s.accept();
out.close();
skt.close();
s.close();
catch(Exception e)
SAMPLE INPUT/OUTPUT:
E:\EX7>javac SerTCP.java
E:\EX7>java SerTCP
Sending string:
Welcome
E:\EX7>javac CliTCP.java
E:\EX7>java CliTCP
Received string:
Welcome
Ex. No. 8.
Date:
Theory
Inet Address
BufferedReader class
The BufferedReader class is used for fast reading operations of texts from a character-
input stream. It can be used to read single characters, arrays, and lines of data. The size of buffer
may or may not be specified. The readLine() method of the BufferedReader class can be used to
get the next line of characters from a file, and the skip(long n) method can be used to skip n
number of characters.
SOURCE CODE FOR CLASS CHAT:
import java.io.*;
import java.net.*;
import java.lang.String.*;
Socket soc;
InetAddress addr;
ServerSocket s;
BufferedReader d;
BufferedReader in;
PrintWriter out;
String name;
soc= s;
start();
}
public void run()
String str;
try
str=in.readLine();
name=str;
addr=soc.getInetAddress();
System.out.println("Message:");
str=d.readLine();
while(true)
out.println(str);
str=in.readLine();
if(str.equalsIgnoreCase("end"))
break;
System.out.println(name+":>"+str);
System.out.println("Message : ");
str=d.readLine();
catch(IOException e)
{}
catch(NullPointerException e)
import java.io.*;
import java.net.*;
class chatclient
try
InetAddress a=InetAddress.getLocalHost();
soc=new Socket(a,0202);
String s;
s=in.readLine();
System.out.println(s);
s=in.readLine();
System.out.println(s);
s=d.readLine();
while(true)
out.println(s);
s=in.readLine();
System.out.println("Server:> "+s);
if(s.equalsIgnoreCase("Chat is closing"))
break;
System.out.println("Message : ");
s=d.readLine();
if(s.equalsIgnoreCase("end"))
break;
finally
soc.close();
}
import java.io.*;
import java.net.*;
class chatserver
try
while(true)
Socket soc=s.accept();
try
new chat(soc);
}
catch(IOException e)
soc.close();
finally
s.close();
SAMPLE INPUT/OUTPUT:
E:\EX8>javac chatserver.java
E:\EX8>java chatserver
Message :
IT:> I am fine.
E:\EX8>javac chatclient.java
name please : BE IT