0% found this document useful (0 votes)
33 views

Network Programming Lab

The document is a lab report detailing various network programming exercises completed by a student in the BCA 6th semester. It includes Java programs for tasks such as retrieving IP addresses, checking address types, handling URLs, managing HTTP cookies, and socket communication. Each lab section contains source code and expected output for the respective programming tasks.

Uploaded by

shital awal
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views

Network Programming Lab

The document is a lab report detailing various network programming exercises completed by a student in the BCA 6th semester. It includes Java programs for tasks such as retrieving IP addresses, checking address types, handling URLs, managing HTTP cookies, and socket communication. Each lab section contains source code and expected output for the respective programming tasks.

Uploaded by

shital awal
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 36

UNIVERSAL COLLEGE

Maitidevi, Kathmandu

Lab Report of Network Programming

Submitted by: Submitted to:


Shital kumar Awal Sunil Chaudhary
BCA 6th Semester

Contents
LAB 1 – write a program to retrieve host name ip address of local machine...........................3
LAB 2 -write a java program to check loopback address, private address , multicast address,
any local address...........................................................................................................................4
LAB 3 – Write a java program to split different components of url from given url................7
Lab 4: Write a java program to find baseurl,relativeurl and resolvedurl from given url
https://samriddhicollege.edu.np/wp-content/uploads/2019/09/Networking_Programming-
Syllabus.zip....................................................................................................................................8
Lab 5:Write a java program to get different parts of URI in given URI=
http://www.xml.com/pub/a/2003/09/17/stax.html#id=_hbc........................................................9
LAB 6 -Write a java program to fetch website content using URLConnectionClass............11
Lab 7: Write a program to handle HTTP cookies in Java using the CookieManager and
HttpCookie classes also retrieve and display cookie information from a specified URL.......13
Lab 8: Write a java program to manage HTTP cookies using the CookieStore and HttpCookie
classes also add, retrieve, and remove cookies from a CookieStore........................................15
LAB 9 – Write a program to fetch all HTTP header Fields using URLConnection..............18
Lab 10: Write a java program to perform url encoding and decoding...................................20
LAB 11- Write a program to read data from server using socket...........................................22
LAB 12 – Write a java program to write data to server using socket.....................................25
LAB 13 – write a java program to serve binary data using socket..........................................28
LAB 14 – Write a Simple UDP java program to send data from client to server..................29
LAB 15- Write a simple chat client server application using nio.............................................31

LAB 1 – write a program to retrieve host name ip address of


local machine

Source code
import java.net.InetAddress;
import java.net.UnknownHostException;

public class Lab1 {


public static void main(String[] args) {
try {

InetAddress localHost = InetAddress.getLocalHost();

String hostName = localHost.getHostName();

String ipAddress = localHost.getHostAddress();

System.out.println("Host Name: " + hostName);


System.out.println("IP Address: " + ipAddress);
} catch (UnknownHostException e) {
System.err.println("Unable to retrieve local host information");
e.printStackTrace();
}
}
}

Output

LAB 2 -write a java program to check loopback address, private


address , multicast address, any local address

Source code
import java.net.InetAddress;
import java.net.UnknownHostException;

public class Lab2{

public static void main(String[] args) {


String[] ipAddresses = {
"127.0.0.1",
"192.168.1.1",
"224.0.0.1",
"0.0.0.0",
"8.8.8.8"
};

for (String ipAddress : ipAddresses) {


try {
InetAddress address = InetAddress.getByName(ipAddress);
System.out.println("Checking IP address: " + ipAddress);
checkAddressType(address);
System.out.println();
} catch (UnknownHostException e) {
System.err.println("Invalid IP address: " + ipAddress);
e.printStackTrace();
}
}
}

public static void checkAddressType(InetAddress address) {


if (address.isLoopbackAddress()) {
System.out.println("This is a loopback address.");
}
if (address.isSiteLocalAddress()) {
System.out.println("This is a private address.");
}
if (address.isMulticastAddress()) {
System.out.println("This is a multicast address.");
}
if (address.isAnyLocalAddress()) {
System.out.println("This is an any local address.");
}
if (!address.isLoopbackAddress() && !address.isSiteLocalAddress() &&
!address.isMulticastAddress() && !address.isAnyLocalAddress()) {
System.out.println("This is a public/global address.");
}
}
}

Output
LAB 3 – Write a java program to split different components of
url from given url

import java.net.MalformedURLException;
import java.net.URL;

public class lab5 {

public static void main(String[] args) throws MalformedURLException {


URL url1 = new URL("https://www.example.com:8080/path/to/resource?
key1=value1&key2=value2#section2");
System.out.println(url1.toString());
System.out.println();
System.out.println(
"Different components of the URL1-");
System.out.println("Protocol:- " + url1.getProtocol());
System.out.println("Hostname:- " + url1.getHost());
System.out.println("Default port:- "+ url1.getDefaultPort());
// Retrieving the query part of URL
System.out.println("Query:- " + url1.getQuery());
// Retrieving the path of URL
System.out.println("Path:- " + url1.getPath());
// Retrieving the file name
System.out.println("File:- " + url1.getFile());
// Retrieving the reference
System.out.println("Reference:- " + url1.getRef());

Output
Lab 4: Write a java program to find baseurl,relativeurl and
resolvedurl from given url https://samriddhicollege.edu.np/wp-
content/uploads/2019/09/Networking_Programming-Syllabus.zip

import java.net.MalformedURLException;
import java.net.URL;

public class lab4 {


public static void main (String[]args)throws MalformedURLException{
String baseurl ="https://samriddhi.college.edu.np/wp-content/uploads/2019/09/";
String relativeurl="Networking_Programming-syllabus.zip";
URL baseUrl = new URL(baseurl);
URL resolvedRelativeUrl = new URL(baseUrl,relativeurl);
System.out.println("BaseUrl:"+baseurl);
System.out.println("Relative Url:"+relativeurl);
System.out.println("Resolved Relative Url:"+resolvedRelativeUrl);
}
}

Output
Lab 5:Write a java program to get different parts of URI in given URI=
http://www.xml.com/pub/a/2003/09/17/stax.html#id=_hbc

import java.net.*;
public class Lab5
{
public static void main(String[] args) throws Exception {
String str ="http://www.xml.com/pub/a/2003/09/17/stax.html#id=_hbc";
URI uri = URI.create(str);
System.out.println(uri.normalize().toString());
System.out.println("Scheme = " + uri.getScheme());
System.out.println("Schemespecificpart = "+ uri.getSchemeSpecificPart());
System.out.println("Raw User Info = " + uri.getFragment());
System.out.println("User Info = " + uri.getUserInfo());
System.out.println("Authority = " + uri.getAuthority());
System.out.println("Host = " + uri.getHost());
System.out.println("Path = " + uri.getPath());
System.out.println("Port = " + uri.getPort());
System.out.println("Query = " + uri.getQuery());

}
}

Output
LAB 6 -Write a java program to fetch website content using
URLConnectionClass

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

public class FetchWebsiteContent {


public static void main(String[] args) {
String urlString = "http://example.com"; // Replace with your desired URL

try {
// Create a URL object
URL url = new URL(urlString);

// Open a connection to the URL


URLConnection urlConnection = url.openConnection();

// Create an InputStreamReader to read the response


BufferedReader reader = new BufferedReader(new
InputStreamReader(urlConnection.getInputStream()));
// Read the content line by line
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}

// Close the reader


reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

Output
Lab 7: Write a program to handle HTTP cookies in Java using the
CookieManager and HttpCookie classes also retrieve and display cookie
information from a specified URL.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

public class CookieHandler {

public static void main(String[] args) {


String url = "http://example.com"; // replace with your URL
CookieManager cookieManager = new CookieManager();
cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);

try {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", "Mozilla/5.0");

// Add cookie manager to the connection


con.setRequestProperty("Cookie",
cookieManager.getCookieStore().getCookies().toString());
int responseCode = con.getResponseCode();
System.out.println("Response Code : " + responseCode);

// Get cookies from the response


List<java.net.HttpCookie> cookies =
cookieManager.getCookieStore().getCookies();
for (java.net.HttpCookie cookie : cookies) {
System.out.println("Cookie Name: " + cookie.getName());
System.out.println("Cookie Value: " + cookie.getValue());
System.out.println("Cookie Domain: " + cookie.getDomain());
System.out.println("Cookie Path: " + cookie.getPath());
System.out.println("Cookie Max Age: " + cookie.getMaxAge());
System.out.println("Cookie Secure: " + cookie.getSecure());
System.out.println("Cookie HttpOnly: " + cookie.isHttpOnly());
System.out.println("Cookie Version: " + cookie.getVersion());
System.out.println("------------------------");
}

// Read the response


BufferedReader in = new BufferedReader(new
InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();

System.out.println(response.toString());

} catch (MalformedURLException e) {
System.out.println("MalformedURLException: " + e.getMessage());
} catch (IOException e) {
System.out.println("IOException: " + e.getMessage());
}
}
}
Output

Lab 8: Write a java program to manage HTTP cookies using the


CookieStore and HttpCookie classes also add, retrieve, and remove
cookies from a CookieStore

import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.CookieStore;
import java.net.HttpCookie;
import java.net.URI;
import java.util.List;

public class CookieManagerExample {

public static void main(String[] args) {


try {
// Create a URI for the cookies (e.g., a specific website or domain)
URI uri = new URI("http://example.com");

// Create a CookieManager with a default CookieStore


CookieManager cookieManager = new CookieManager();
cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);

// Get the CookieStore from the CookieManager


CookieStore cookieStore = cookieManager.getCookieStore();

// Add a new cookie to the CookieStore


HttpCookie cookie = new HttpCookie("username", "john_doe");
cookie.setDomain("example.com");
cookie.setPath("/");
cookieStore.add(uri, cookie);
System.out.println("Cookie added: " + cookie);

// Retrieve all cookies from the CookieStore


List<HttpCookie> cookies = cookieStore.get(uri);
System.out.println("\nCookies retrieved:");
for (HttpCookie retrievedCookie : cookies) {
System.out.println("Cookie: " + retrievedCookie.getName() + " = " +
retrievedCookie.getValue());
}

// Remove a specific cookie from the CookieStore


cookieStore.remove(uri, cookie);
System.out.println("\nCookie removed: " + cookie);

// Verify that the cookie has been removed


cookies = cookieStore.get(uri);
System.out.println("\nCookies after removal:");
if (cookies.isEmpty()) {
System.out.println("No cookies found.");
} else {
for (HttpCookie retrievedCookie : cookies) {
System.out.println("Cookie: " + retrievedCookie.getName() + " = " +
retrievedCookie.getValue());
}
}

} catch (Exception e) {
e.printStackTrace();
}
}
}

Output
LAB 9 – Write a program to fetch all HTTP header Fields using
URLConnection

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

public class FetchHttpHeaders {


public static void main(String[] args) throws IOException {
URL url = new URL("https://www.example.com"); // replace with your URL
URLConnection connection = url.openConnection();

// Get the HTTP headers


System.out.println("HTTP Headers:");
for (String header : connection.getHeaderFields().keySet()) {
System.out.println(header + ": " + connection.getHeaderField(header));
}

// Get the response content


BufferedReader reader = new BufferedReader(new
InputStreamReader(connection.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
}
}

Output
Lab 10: Write a java program to perform url encoding and
decoding.

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.net.URLDecoder;

public class URLEncodeDecode {

public static void main(String[] args) {


String originalString = "Hello World! 50% off on all items.";
String charset = "UTF-8";

try {
// URL Encoding
String encodedString = URLEncoder.encode(originalString, charset);
System.out.println("Encoded String: " + encodedString);

// URL Decoding
String decodedString = URLDecoder.decode(encodedString, charset);
System.out.println("Decoded String: " + decodedString);

} catch (UnsupportedEncodingException e) {
System.err.println("Encoding not supported: " + e.getMessage());
}
}
}
Output

LAB 11- Write a program to read data from server using socket

Client
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

public class SocketClient {


public static void main(String[] args) throws IOException {
// Create a socket object
Socket socket = new Socket("localhost", 8080); // replace with server IP and port

// Create a BufferedReader to read data from the server


BufferedReader reader = new BufferedReader(new
InputStreamReader(socket.getInputStream()));

// Read data from the server


String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}

// Close the socket


socket.close();
}
}

Server
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class SocketServer {
public static void main(String[] args) throws IOException {
// Create a server socket
ServerSocket serverSocket = new ServerSocket(8080);

// Accept incoming connections


Socket socket = serverSocket.accept();

// Create a PrintWriter to send data to the client


PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);

// Send data to the client


writer.println("Hello, client!");
writer.println("This is a test message.");

// Close the socket


socket.close();
}
}
Output
LAB 12 – Write a java program to write data to server using
socket

Client

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class lab12a {


public static void main(String[] args) throws IOException {
// Create a socket object
Socket socket = new Socket("localhost", 8080); // replace with server IP and port

// Create a PrintWriter to send data to the server


PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
// Create a BufferedReader to read user input
BufferedReader userInputReader = new BufferedReader(new
InputStreamReader(System.in));

// Write data to the server


System.out.print("Enter a message to send to the server: ");
String message = userInputReader.readLine();
writer.println(message);

// Read response from the server


BufferedReader serverResponseReader = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
String response = serverResponseReader.readLine();
System.out.println("Server response: " + response);

// Close the socket


socket.close();
}
}

Server
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class lab12b {


public static void main(String[] args) throws IOException {
// Create a server socket
ServerSocket serverSocket = new ServerSocket(8080);
// Accept incoming connections
Socket socket = serverSocket.accept();

// Create a BufferedReader to read data from the client


BufferedReader reader = new BufferedReader(new
InputStreamReader(socket.getInputStream()));

// Create a PrintWriter to send data to the client


PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);

// Read data from the client


String message = reader.readLine();
System.out.println("Received message from client: " + message);

// Send response to the client


writer.println("Hello, client! I received your message.");

// Close the socket


socket.close();
}
}

Output
LAB 13 – write a java program to serve binary data using socket.

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

public class BinaryDataClient {


public static void main(String[] args) {
Socket socket = null;
DataInputStream dataIn = null;

try {
// Connect to the server on localhost, port 5000
socket = new Socket("localhost", 5000);
System.out.println("Connected to server!");

// Prepare the input stream to receive binary data


dataIn = new DataInputStream(socket.getInputStream());

// Read and display the binary data from the server


byte[] buffer = new byte[5]; // Same size as the data we expect
dataIn.readFully(buffer); // Read the full binary data

System.out.println("Binary data received from server:");


for (byte b : buffer) {
System.out.printf("0x%02X ", b); // Print data in hexadecimal format
}
System.out.println();

} catch (IOException e) {
e.printStackTrace();
} finally {
// Close resources
try {
if (dataIn != null) dataIn.close();
if (socket != null) socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

Server
import java.io.*;
import java.net.*;
public class BinaryDataServer {
public static void main(String[] args) {
ServerSocket serverSocket = null;
Socket clientSocket = null;
DataOutputStream dataOut = null;

try {
// Create a server socket that listens on port 5000
serverSocket = new ServerSocket(5000);
System.out.println("Server is listening on port 5000...");

// Wait for a client to connect


clientSocket = serverSocket.accept();
System.out.println("Client connected!");

// Prepare the output stream to send binary data


dataOut = new DataOutputStream(clientSocket.getOutputStream());

// Example: Send a binary data sequence


byte[] binaryData = {0x01, 0x02, 0x03, 0x04, 0x05}; // Sample binary data

// Send the binary data to the client


dataOut.write(binaryData);
dataOut.flush();

System.out.println("Binary data sent to client.");

} catch (IOException e) {
e.printStackTrace();
} finally {
// Close resources
try {
if (dataOut != null) dataOut.close();
if (clientSocket != null) clientSocket.close();
if (serverSocket != null) serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

Output
LAB 14 – Write a Simple UDP java program to send data from client to
server

Client
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class udpclient {


public static void main(String[] args)throws Exception{
DatagramSocket clientSocket = new DatagramSocket();
String message ="Hello, UDP Server!";
byte[] sbuffer = message.getBytes();
InetAddress servAddress = InetAddress.getByName("localhost");
DatagramPacket sendpacket = new DatagramPacket(sbuffer,
sbuffer.length,servAddress,5000);
clientSocket.send(sendpacket);
clientSocket.close();

Server
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class udpserver {
public static void main(String[] args) {
try{
DatagramSocket serverSocket = new DatagramSocket(5000);
byte[] receiveBuffer = new byte[1024];
DatagramPacket receivPacket= new DatagramPacket(receiveBuffer,
receiveBuffer.length);
System.out.println("Server is waiting for a packet...");
serverSocket.receive(receivPacket);
String receivedMessage = new
String(receivPacket.getData(),0,receivPacket.getLength());
System.out.println("Received:"+receivedMessage);
serverSocket.close();
}catch(Exception e){
e.printStackTrace();
}
}

Output
LAB 15- Write a simple chat client server application using nio

Client
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.nio.channels.SocketChannel;
import java.util.Scanner;

public class chatclient {


public chatclient(){
SocketAddress address =new InetSocketAddress("127.0.0.1",5000);
try (SocketChannel socketChannel=SocketChannel.open(address)){
System.out.println("Connected to chat server");
String message;
Scanner scanner= new Scanner(System.in);
while (true) {
System.out.println("waiting for message from the server...");

}
}catch (IOException ex){
ex.printStackTrace();
}
}

public static void main (String[] args) {


new chatclient();
}
}
Server
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

public class chatserver {


public static void main(String[] args) {
System.out.println("chat Server is started");
try{
ServerSocketChannel serverSocketChannel=ServerSocketChannel.open();
serverSocketChannel.socket().bind(new InetSocketAddress(5000));
boolean running= true;
while (running) {
System.out.println("Waiting for request...");
SocketChannel socketChannel =serverSocketChannel.accept();

}
}
catch(IOException ex){
ex.printStackTrace();
}

}
}

Output

You might also like