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
[Link]
[Link]....................................................................................................................................8
Lab 5:Write a java program to get different parts of URI in given URI=
[Link]
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 [Link];
import [Link];
public class Lab1 {
public static void main(String[] args) {
try {
InetAddress localHost = [Link]();
String hostName = [Link]();
String ipAddress = [Link]();
[Link]("Host Name: " + hostName);
[Link]("IP Address: " + ipAddress);
} catch (UnknownHostException e) {
[Link]("Unable to retrieve local host information");
[Link]();
}
}
}
Output
LAB 2 -write a java program to check loopback address, private
address , multicast address, any local address
Source code
import [Link];
import [Link];
public class Lab2{
public static void main(String[] args) {
String[] ipAddresses = {
"[Link]",
"[Link]",
"[Link]",
"[Link]",
"[Link]"
};
for (String ipAddress : ipAddresses) {
try {
InetAddress address = [Link](ipAddress);
[Link]("Checking IP address: " + ipAddress);
checkAddressType(address);
[Link]();
} catch (UnknownHostException e) {
[Link]("Invalid IP address: " + ipAddress);
[Link]();
}
}
}
public static void checkAddressType(InetAddress address) {
if ([Link]()) {
[Link]("This is a loopback address.");
}
if ([Link]()) {
[Link]("This is a private address.");
}
if ([Link]()) {
[Link]("This is a multicast address.");
}
if ([Link]()) {
[Link]("This is an any local address.");
}
if (![Link]() && ![Link]() &&
![Link]() && ![Link]()) {
[Link]("This is a public/global address.");
}
}
}
Output
LAB 3 – Write a java program to split different components of
url from given url
import [Link];
import [Link];
public class lab5 {
public static void main(String[] args) throws MalformedURLException {
URL url1 = new URL("[Link]
key1=value1&key2=value2#section2");
[Link]([Link]());
[Link]();
[Link](
"Different components of the URL1-");
[Link]("Protocol:- " + [Link]());
[Link]("Hostname:- " + [Link]());
[Link]("Default port:- "+ [Link]());
// Retrieving the query part of URL
[Link]("Query:- " + [Link]());
// Retrieving the path of URL
[Link]("Path:- " + [Link]());
// Retrieving the file name
[Link]("File:- " + [Link]());
// Retrieving the reference
[Link]("Reference:- " + [Link]());
Output
Lab 4: Write a java program to find baseurl,relativeurl and
resolvedurl from given url [Link]
content/uploads/2019/09/Networking_Programming-[Link]
import [Link];
import [Link];
public class lab4 {
public static void main (String[]args)throws MalformedURLException{
String baseurl ="[Link]
String relativeurl="Networking_Programming-[Link]";
URL baseUrl = new URL(baseurl);
URL resolvedRelativeUrl = new URL(baseUrl,relativeurl);
[Link]("BaseUrl:"+baseurl);
[Link]("Relative Url:"+relativeurl);
[Link]("Resolved Relative Url:"+resolvedRelativeUrl);
}
}
Output
Lab 5:Write a java program to get different parts of URI in given URI=
[Link]
import [Link].*;
public class Lab5
{
public static void main(String[] args) throws Exception {
String str ="[Link]
URI uri = [Link](str);
[Link]([Link]().toString());
[Link]("Scheme = " + [Link]());
[Link]("Schemespecificpart = "+ [Link]());
[Link]("Raw User Info = " + [Link]());
[Link]("User Info = " + [Link]());
[Link]("Authority = " + [Link]());
[Link]("Host = " + [Link]());
[Link]("Path = " + [Link]());
[Link]("Port = " + [Link]());
[Link]("Query = " + [Link]());
}
}
Output
LAB 6 -Write a java program to fetch website content using
URLConnectionClass
import [Link];
import [Link];
import [Link];
import [Link];
public class FetchWebsiteContent {
public static void main(String[] args) {
String urlString = "[Link] // Replace with your desired URL
try {
// Create a URL object
URL url = new URL(urlString);
// Open a connection to the URL
URLConnection urlConnection = [Link]();
// Create an InputStreamReader to read the response
BufferedReader reader = new BufferedReader(new
InputStreamReader([Link]()));
// Read the content line by line
String line;
while ((line = [Link]()) != null) {
[Link](line);
}
// Close the reader
[Link]();
} catch (Exception e) {
[Link]();
}
}
}
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 [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class CookieHandler {
public static void main(String[] args) {
String url = "[Link] // replace with your URL
CookieManager cookieManager = new CookieManager();
[Link](CookiePolicy.ACCEPT_ALL);
try {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) [Link]();
[Link]("GET");
[Link]("User-Agent", "Mozilla/5.0");
// Add cookie manager to the connection
[Link]("Cookie",
[Link]().getCookies().toString());
int responseCode = [Link]();
[Link]("Response Code : " + responseCode);
// Get cookies from the response
List<[Link]> cookies =
[Link]().getCookies();
for ([Link] cookie : cookies) {
[Link]("Cookie Name: " + [Link]());
[Link]("Cookie Value: " + [Link]());
[Link]("Cookie Domain: " + [Link]());
[Link]("Cookie Path: " + [Link]());
[Link]("Cookie Max Age: " + [Link]());
[Link]("Cookie Secure: " + [Link]());
[Link]("Cookie HttpOnly: " + [Link]());
[Link]("Cookie Version: " + [Link]());
[Link]("------------------------");
}
// Read the response
BufferedReader in = new BufferedReader(new
InputStreamReader([Link]()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = [Link]()) != null) {
[Link](inputLine);
}
[Link]();
[Link]([Link]());
} catch (MalformedURLException e) {
[Link]("MalformedURLException: " + [Link]());
} catch (IOException e) {
[Link]("IOException: " + [Link]());
}
}
}
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 [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
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("[Link]
// Create a CookieManager with a default CookieStore
CookieManager cookieManager = new CookieManager();
[Link](CookiePolicy.ACCEPT_ALL);
// Get the CookieStore from the CookieManager
CookieStore cookieStore = [Link]();
// Add a new cookie to the CookieStore
HttpCookie cookie = new HttpCookie("username", "john_doe");
[Link]("[Link]");
[Link]("/");
[Link](uri, cookie);
[Link]("Cookie added: " + cookie);
// Retrieve all cookies from the CookieStore
List<HttpCookie> cookies = [Link](uri);
[Link]("\nCookies retrieved:");
for (HttpCookie retrievedCookie : cookies) {
[Link]("Cookie: " + [Link]() + " = " +
[Link]());
}
// Remove a specific cookie from the CookieStore
[Link](uri, cookie);
[Link]("\nCookie removed: " + cookie);
// Verify that the cookie has been removed
cookies = [Link](uri);
[Link]("\nCookies after removal:");
if ([Link]()) {
[Link]("No cookies found.");
} else {
for (HttpCookie retrievedCookie : cookies) {
[Link]("Cookie: " + [Link]() + " = " +
[Link]());
}
}
} catch (Exception e) {
[Link]();
}
}
}
Output
LAB 9 – Write a program to fetch all HTTP header Fields using
URLConnection
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class FetchHttpHeaders {
public static void main(String[] args) throws IOException {
URL url = new URL("[Link] // replace with your URL
URLConnection connection = [Link]();
// Get the HTTP headers
[Link]("HTTP Headers:");
for (String header : [Link]().keySet()) {
[Link](header + ": " + [Link](header));
}
// Get the response content
BufferedReader reader = new BufferedReader(new
InputStreamReader([Link]()));
String line;
while ((line = [Link]()) != null) {
[Link](line);
}
[Link]();
}
}
Output
Lab 10: Write a java program to perform url encoding and
decoding.
import [Link];
import [Link];
import [Link];
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 = [Link](originalString, charset);
[Link]("Encoded String: " + encodedString);
// URL Decoding
String decodedString = [Link](encodedString, charset);
[Link]("Decoded String: " + decodedString);
} catch (UnsupportedEncodingException e) {
[Link]("Encoding not supported: " + [Link]());
}
}
}
Output
LAB 11- Write a program to read data from server using socket
Client
import [Link];
import [Link];
import [Link];
import [Link];
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([Link]()));
// Read data from the server
String line;
while ((line = [Link]()) != null) {
[Link](line);
}
// Close the socket
[Link]();
}
}
Server
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
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 = [Link]();
// Create a PrintWriter to send data to the client
PrintWriter writer = new PrintWriter([Link](), true);
// Send data to the client
[Link]("Hello, client!");
[Link]("This is a test message.");
// Close the socket
[Link]();
}
}
Output
LAB 12 – Write a java program to write data to server using
socket
Client
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
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([Link](), true);
// Create a BufferedReader to read user input
BufferedReader userInputReader = new BufferedReader(new
InputStreamReader([Link]));
// Write data to the server
[Link]("Enter a message to send to the server: ");
String message = [Link]();
[Link](message);
// Read response from the server
BufferedReader serverResponseReader = new BufferedReader(new
InputStreamReader([Link]()));
String response = [Link]();
[Link]("Server response: " + response);
// Close the socket
[Link]();
}
}
Server
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
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 = [Link]();
// Create a BufferedReader to read data from the client
BufferedReader reader = new BufferedReader(new
InputStreamReader([Link]()));
// Create a PrintWriter to send data to the client
PrintWriter writer = new PrintWriter([Link](), true);
// Read data from the client
String message = [Link]();
[Link]("Received message from client: " + message);
// Send response to the client
[Link]("Hello, client! I received your message.");
// Close the socket
[Link]();
}
}
Output
LAB 13 – write a java program to serve binary data using socket.
Client
import [Link].*;
import [Link].*;
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);
[Link]("Connected to server!");
// Prepare the input stream to receive binary data
dataIn = new DataInputStream([Link]());
// Read and display the binary data from the server
byte[] buffer = new byte[5]; // Same size as the data we expect
[Link](buffer); // Read the full binary data
[Link]("Binary data received from server:");
for (byte b : buffer) {
[Link]("0x%02X ", b); // Print data in hexadecimal format
}
[Link]();
} catch (IOException e) {
[Link]();
} finally {
// Close resources
try {
if (dataIn != null) [Link]();
if (socket != null) [Link]();
} catch (IOException e) {
[Link]();
}
}
}
}
Server
import [Link].*;
import [Link].*;
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);
[Link]("Server is listening on port 5000...");
// Wait for a client to connect
clientSocket = [Link]();
[Link]("Client connected!");
// Prepare the output stream to send binary data
dataOut = new DataOutputStream([Link]());
// Example: Send a binary data sequence
byte[] binaryData = {0x01, 0x02, 0x03, 0x04, 0x05}; // Sample binary data
// Send the binary data to the client
[Link](binaryData);
[Link]();
[Link]("Binary data sent to client.");
} catch (IOException e) {
[Link]();
} finally {
// Close resources
try {
if (dataOut != null) [Link]();
if (clientSocket != null) [Link]();
if (serverSocket != null) [Link]();
} catch (IOException e) {
[Link]();
}
}
}
}
Output
LAB 14 – Write a Simple UDP java program to send data from client to
server
Client
import [Link];
import [Link];
import [Link];
public class udpclient {
public static void main(String[] args)throws Exception{
DatagramSocket clientSocket = new DatagramSocket();
String message ="Hello, UDP Server!";
byte[] sbuffer = [Link]();
InetAddress servAddress = [Link]("localhost");
DatagramPacket sendpacket = new DatagramPacket(sbuffer,
[Link],servAddress,5000);
[Link](sendpacket);
[Link]();
Server
import [Link];
import [Link];
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,
[Link]);
[Link]("Server is waiting for a packet...");
[Link](receivPacket);
String receivedMessage = new
String([Link](),0,[Link]());
[Link]("Received:"+receivedMessage);
[Link]();
}catch(Exception e){
[Link]();
}
}
Output
LAB 15- Write a simple chat client server application using nio
Client
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class chatclient {
public chatclient(){
SocketAddress address =new InetSocketAddress("[Link]",5000);
try (SocketChannel socketChannel=[Link](address)){
[Link]("Connected to chat server");
String message;
Scanner scanner= new Scanner([Link]);
while (true) {
[Link]("waiting for message from the server...");
}
}catch (IOException ex){
[Link]();
}
}
public static void main (String[] args) {
new chatclient();
}
}
Server
import [Link];
import [Link];
import [Link];
import [Link];
public class chatserver {
public static void main(String[] args) {
[Link]("chat Server is started");
try{
ServerSocketChannel serverSocketChannel=[Link]();
[Link]().bind(new InetSocketAddress(5000));
boolean running= true;
while (running) {
[Link]("Waiting for request...");
SocketChannel socketChannel =[Link]();
}
}
catch(IOException ex){
[Link]();
}
}
}
Output