A
LAB REPORT
ON
NETWORK PROGRAMMING
By
Prajwal Dahal
TU REG no: 6-2-388-03-2019
Submitted to:
Harendra Subedi
Lecturer
Kantipur College of Management and Information Technology
In partial fulfillment of the requirements for the Course
Network Programming
Mid Baneshwor, Kathmandu
December 2023
TABLE OF CONTENTS
Write a program to display IP address of ‘[Link]’ by using
InetAddress class. ................................................... 1
Source Code ................................................... 1
Output Window ................................................. 1
Write a program to display mac address and IP Address of your pc. 2
Source Code ................................................... 2
Output Window ................................................. 3
Write a program to retrieve protocol, port, host and file from URL.
4
Source Code ................................................... 4
Output Window ................................................. 4
Write a program to construct URI with schema, authority, path,
query and fragments. ................................................. 5
Source Code ................................................... 5
Output Windows ................................................ 5
Write a program to demonstrate use of URLEncoder and URLDecoder
class. ............................................................... 6
Source Code ................................................... 6
Output Window ................................................. 6
Write a program to set the cookie and retrieved cookie using
CookieManager class. ................................................. 7
Source Code ................................................... 7
Output Window ................................................. 8
Write a program to read data from the server. .................... 9
Source Code ................................................... 9
Output Window ................................................ 10
Write a Program to retrieve specific header fields. ............. 11
Source Code .................................................. 11
Output Window ................................................ 12
Write a program to demonstrate client-server communication using
Socket. ............................................................. 13
Source Code .................................................. 13
Output Window ................................................ 15
Write a Program to demonstrate Multithreaded Server. ........... 16
Source Code ................................................ 16
Output Window .............................................. 19
Write a program to demonstrate daytime client. ................. 20
Source Code ................................................... 20
Output Window .............................................. 20
Write a program to demonstrate client-server communication using
UDP protocol. ....................................................... 21
Source Code ................................................ 21
Output Window .............................................. 22
Write a Program to demonstrate multicast communication. ........ 24
Source Code ................................................ 24
Output Window .............................................. 26
Write a Program to demonstrate secure socket. .................. 27
Source Code ................................................ 27
Output Windows ............................................. 29
Write a program to add two numbers using RMI. .................. 30
Source code ................................................ 30
Output Window .............................................. 31
Write program to implement the concept on Filling and Draining
buffer, Duplicating buffer, Slicing buffer and Compact buffer. ...... 33
Source code ................................................ 33
Output window .............................................. 34
Write a program to display IP address of ‘[Link]’ by using InetAddress
class.
Source Code
package qstn;
import [Link];
import [Link];
public class GoogleIpAddress {
public static void main(String[] args) {
try
{
InetAddress address =
[Link]("[Link]");
[Link]("IP address: " +
[Link]());
} catch (UnknownHostException e) {
[Link]("Hostname not found");
}
}
}
Output Window
1
Write a program to display mac address and IP Address of your pc.
Source Code
package qstn;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class IPAddressMACAddress {
public static void main(String[] args) throws SocketException,
UnknownHostException {
InetAddress localhost = [Link]();
String ipAddress = [Link]();
[Link]("IP Address: " + ipAddress);
Enumeration<NetworkInterface> interfaces =
[Link]();
while ([Link]()) {
NetworkInterface interface1 =
[Link]();
byte[] macAddress = [Link]();
if (macAddress != null) {
String macAddressStr = "";
for (int i = 0; i < [Link]; i++) {
macAddressStr +=
[Link]("%02X",macAddress[i]);
if (i < [Link] - 1) {
2
macAddressStr += ":";
}
}
[Link]("MAC Address: " +
macAddressStr);
}
}
}
}
Output Window
3
Write a program to retrieve protocol, port, host and file from URL.
Source Code
import [Link];
import [Link];
public class URLExample {
public static void main(String[] args) {
try {
URL url = new
URL("[Link]
[Link]("Protocol: " + [Link]());
[Link]("Host: " + [Link]());
[Link]("Port: " + [Link]());
[Link]("File: " + [Link]());
} catch (MalformedURLException e) {
[Link]();
}
}
}
Output Window
4
Write a program to construct URI with schema, authority, path, query and
fragments.
Source Code
import [Link];
import [Link];
public class URITestCreate1 {
public static void main(String[] args) {
try {
URI uri = new URI("https", "[Link]", "/path",
"query=param","DCfragment");
[Link]("URI: " + [Link]());
} catch (URISyntaxException e) {
[Link]();
}
}
}
Output Windows
5
Write a program to demonstrate use of URLEncoder and URLDecoder class.
Source Code
import [Link];
import [Link];
import [Link];
public class URLEncoderExample {
public static void main(String[] args) {
try {
String url = "[Link]
String encodedString = [Link](url, "UTF-
8");
[Link]("Encoded String: " +
encodedString);
String decodedString =
[Link](encodedString, "UTF-8");
[Link]("Decoded String: " +
decodedString);
} catch (UnsupportedEncodingException e) {
[Link]();
}
}
}
Output Window
6
Write a program to set the cookie and retrieved cookie using
CookieManager class.
Source Code
package qstn;
import [Link].*;
import [Link];
public class CookieStoreExample {
public static void main(String[] args) throws
URISyntaxException {
CookieManager cookieManager = new CookieManager();
CookieStore cookieStore = [Link]();
URI uri= new URI("[Link]
HttpCookie cookie = new HttpCookie("name", "value");
[Link]([Link]());
[Link]("/");
[Link](1000);
[Link](uri, cookie);
List<HttpCookie> retrievedCookie = [Link](uri);
[Link](retrievedCookie);
for(HttpCookie cookie1:retrievedCookie){
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
}
[Link](uri, cookie);
}
}
7
Output Window
8
Write a program to read data from the server.
Source Code
package qstn;
import [Link].*;
import [Link].*;
public class URLDataRetrievalExample {
public static void main(String[] args) {
String url = "[Link]
try {
URL Url = new URL(url);
HttpURLConnection httpURLConnection = (HttpURLConnection)
[Link]();
InputStream inputStream=[Link]();
InputStreamReader inputStreamReader=new
InputStreamReader(inputStream);
BufferedReader reader=new
BufferedReader(inputStreamReader);
String line;
while ((line = [Link]()) != null) {
[Link](line);
}
[Link]();
} catch (IOException e) {
[Link]();
}
}
}
9
Output Window
10
Write a Program to retrieve specific header fields.
Source Code
package qstn;
import [Link].*;
import [Link].*;
import [Link].*;
public class HeaderFieldExample {
public static void main(String[] args) {
try {
URL url = new URL("[Link]
HttpURLConnection connection = (HttpURLConnection)
[Link]();
String contentType = [Link]();
int contentLength = [Link]();
String contentEncoding =
[Link]();
Date date = new Date([Link]());
Date lastModified = new
Date([Link]());
Date expires = new Date([Link]());
[Link]("Content-Type: " + contentType);
[Link]("Content-Length: " +
contentLength);
[Link]("Content-Encoding: " +
contentEncoding);
[Link]("Date: " + date);
[Link]("Last-Modified: " + lastModified);
[Link]("Expires: " + expires);
[Link]();
11
} catch (IOException e) {
[Link]();
}
}
}
Output Window
12
Write a program to demonstrate client-server communication using Socket.
Source Code
package qstn;
import [Link];
import [Link];
import [Link];
import [Link];
public class Server {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(12345);
[Link]("Server started");
Socket clientSocket = [Link]();
[Link]("Client connected");
OutputStream outputStream =
[Link]();
String message = "Hello client!";
[Link]([Link]());
[Link]("Message sent");
[Link]();
} catch (IOException e) {
[Link]();
}
}
}
package qstn;
import [Link];
import [Link];
13
import [Link];
public class Client {
public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 12345);
[Link]("Connected to server");
InputStream inputStream = [Link]();
byte[] buffer= new byte[1234];
int bytesRead = [Link](buffer);
String message = new String(buffer, 0, bytesRead);
[Link]("Received message: " + message);
[Link]();
} catch (IOException e) {
[Link]();
}
}
}
14
Output Window
15
Write a Program to demonstrate Multithreaded Server.
Source Code
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class MultiThreadedServer {
public static void main(String[] args) {
final int PORT = 12345;
try (ServerSocket serverSocket = new ServerSocket(PORT)) {
[Link]("Server listening on port " + PORT);
while (true) {
Socket clientSocket = [Link]();
[Link]("New connection from " +
[Link]());
Thread clientThread = new Thread(() ->
handleClient(clientSocket));
[Link]();
}
} catch (IOException e) {
[Link]();
}
}
private static void handleClient(Socket clientSocket) {
try (
Scanner input = new
Scanner([Link]());
16
PrintWriter output = new
PrintWriter([Link](), true)
) {
while ([Link]()) {
String clientMessage = [Link]();
[Link]("Received from " +
[Link]() + ": " + clientMessage);
[Link]("Server: " + clientMessage);
}
} catch (IOException e) {
[Link]();
} finally {
[Link]("Connection with " +
[Link]() + " closed.");
try {
[Link]();
} catch (IOException e) {
[Link]();
}
}
}
}
import [Link];
import [Link];
import [Link];
import [Link];
public class Client {
public static void main(String[] args) {
final String SERVER_HOST = "localhost";
final int SERVER_PORT = 12345;
17
try (
Socket socket = new Socket(SERVER_HOST, SERVER_PORT);
Scanner scanner = new Scanner([Link]);
PrintWriter output = new
PrintWriter([Link](), true)
) {
[Link]("Connected to the server.");
Thread receiveThread = new Thread(() -> {
try (Scanner input = new
Scanner([Link]())) {
while ([Link]()) {
[Link]("Server: " +
[Link]());
}
} catch (IOException e) {
[Link]();
}
});
[Link]();
while (true) {
[Link]("Client: ");
String message = [Link]();
[Link](message);
}
} catch (IOException e) {
[Link]();
}
}
18
}
Output Window
19
Write a program to demonstrate daytime client.
Source Code
import [Link].*;
import [Link].*;
public class DayTimeClient {
public static void main(String[] args) {
try {
Socket theSocket = new Socket("[Link]", 13); //
Connect to the server on port 13 (Daytime)
InputStream timeStream = [Link]();
BufferedReader bufferedReader=new BufferedReader(new
InputStreamReader(timeStream));
String line;
while ((line = [Link]()) != null) {
[Link](line);
}
[Link]();
} catch (IOException ex) {
[Link]([Link]());
}
}
}
Output Window
20
Write a program to demonstrate client-server communication using UDP
protocol.
Source Code
import [Link];
import [Link];
import [Link];
public class UdpServer {
public static void main(String[] args) throws IOException {
DatagramSocket datagramSocket=new DatagramSocket(9876);
byte[]buffer =new byte[1024];
DatagramPacket datagramPacket=new
DatagramPacket(buffer,[Link]);
[Link](datagramPacket);
byte[]sendData=[Link]();
DatagramPacket datagramPacket1=new
DatagramPacket(sendData,[Link],[Link]
ddress(),[Link]());
[Link](datagramPacket1);
}
}
import [Link];
import [Link].*;
import [Link];
public class UdpClient {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner([Link]);
String message =[Link]();
21
DatagramSocket clientSocket=new DatagramSocket();
byte[] sendbytes=[Link]();
byte[]buffer=new byte[1024];
DatagramPacket datagramPacket=new
DatagramPacket(sendbytes,[Link],
[Link]("localhost"),9876);
[Link](datagramPacket);
DatagramPacket recieve=new
DatagramPacket(buffer,[Link]);
[Link](recieve);
byte[]x=[Link]();
[Link](new String(x).trim());
}
}
Output Window
22
23
Write a Program to demonstrate multicast communication.
Source Code
import [Link];
import [Link];
import [Link];
public class MulticastReceiver {
public static void main(String[] args) {
try {
int port = 12345;
InetAddress group = [Link]("[Link]");
MulticastSocket socket = new MulticastSocket(port);
[Link](group);
byte[] buffer = new byte[1024];
while (true) {
DatagramPacket packet = new DatagramPacket(buffer,
[Link]);
[Link](packet);
String message = new String([Link](), 0,
[Link]());
[Link]("Received: " + message);
}
} catch (Exception e) {
[Link]();
}
}
}
24
import [Link];
import [Link].*;
import [Link];
public class MulticastClient {
public static void main(String[] args) {
try {
[Link]("enter a number: ");
Scanner sc= new Scanner([Link]);
String message =[Link]();
byte[] sendBuffer = [Link]();
InetAddress multicastGroup =
[Link]("[Link]");
int port = 12345;
MulticastSocket socket = new MulticastSocket();
[Link](multicastGroup);
DatagramPacket sendPacket = new DatagramPacket(sendBuffer,
[Link], multicastGroup, port);
[Link](sendPacket);
byte[] receiveBuffer = new byte[1024];
DatagramPacket receivePacket = new
DatagramPacket(receiveBuffer, [Link]);
[Link](receivePacket);
String receivedMessage = new
String([Link](),
0,[Link]());
[Link]("Server says: " + receivedMessage);
[Link](multicastGroup);
[Link]();
} catch (IOException e) {
25
[Link]();
}
}
}
Output Window
26
Write a Program to demonstrate secure socket.
Source Code
import [Link];
import [Link];
import [Link];
import [Link];
import [Link].*;
public class HTTPClient {
public static void main(String[] args) {
int port = 443;
String host = "[Link]";
try {
SSLSocketFactory factory
= (SSLSocketFactory) [Link]( );
SSLSocket socket = (SSLSocket)
[Link](host, port);
[Link](handshakeComplete
dEvent -> [Link]("handshake completed"));
String[] supported = [Link](
);
[Link](supported);
Writer out = new
OutputStreamWriter([Link]( ));
[Link]("GET [Link] + host + "/ HTTP/1.1\r\n");
[Link]("Host: " + host + "\r\n");
[Link]("\r\n");
[Link]( );
BufferedReader in = new BufferedReader(
27
new InputStreamReader([Link]( )));
String s;
while (!(s = [Link]( )).equals("")) {
[Link](s);
}
[Link]( );
String contentLength = [Link]( );
int length = Integer.MAX_VALUE;
try {
length = [Link]([Link]( ), 16);
}
catch (NumberFormatException ex) {
[Link]();
}
[Link](contentLength);
String c;
int i = 0;
while ((c = [Link]() )!=null && i++ < length) {
[Link](c);
}
[Link]( );
[Link]( );
[Link]( );
[Link]( );
}catch (IOException ex) {
[Link](ex);
}
}}
28
Output Windows
29
Write a program to add two numbers using RMI.
Source code
package RMI;
import [Link];
import [Link];
public interface Adder extends Remote {
int add(int a, int b) throws RemoteException;
}
package RMI;
import [Link];
import [Link];
public class AdderImpl extends UnicastRemoteObject implements Adder {
public AdderImpl() throws RemoteException {
super();
}
public int add(int a, int b) throws RemoteException {
return a + b;
}
}
package RMI;
import [Link];
import [Link];
public class AdderServer {
public static void main(String[] args) {
try {
Adder adder = new AdderImpl();
Registry registry = [Link](1099);
[Link]("Adder", adder);
30
[Link]("Server is ready to accept
requests...");
} catch (Exception e) {
[Link]();
}
}
}
package RMI;
import [Link];
import [Link];
public class AdderClient {
public static void main(String[] args) {
try {
Registry registry =
[Link]("localhost", 1099);
Adder adder = (Adder) [Link]("Adder");
int result = [Link](5, 10);
[Link]("Result from server: " + result);
} catch (Exception e) {
[Link]();
}
}
}
Output Window
31
32
Write program to implement the concept on Filling and Draining buffer,
Duplicating buffer, Slicing buffer and Compact buffer.
Source code
package qstn;
import [Link];
public class ByteBufferOperations {
public static void main(String[] args) {
ByteBuffer buffer = [Link](10);
for (int i = 1; i <= 5; i++) {
[Link]((byte) i);
}
[Link]("Original Buffer: " +
byteArrayToHexString([Link]()));
[Link]();
while ([Link]()) {
[Link]("Drained Byte: " + [Link]());
}
ByteBuffer duplicateBuffer = [Link]();
[Link]("Duplicated Buffer: " +
byteArrayToHexString([Link]()));
[Link]();
[Link](new byte[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10});
[Link](3).limit(7);
ByteBuffer slicedBuffer = [Link]();
[Link]("Sliced Buffer: " +
byteArrayToHexString([Link]()));
[Link]();
[Link](new byte[]{1, 2, 3, 4, 5});
[Link]();
33
[Link]();
[Link]();
[Link]("Compacted Buffer: " +
byteArrayToHexString([Link]()));
}
private static String byteArrayToHexString(byte[] array) {
StringBuilder hexString = new StringBuilder();
for (byte b : array) {
[Link]([Link]("%02X ", b));
}
return [Link]().trim();
}
}
Output window
34