0% found this document useful (0 votes)
329 views36 pages

Network Programming Lab Report

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
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
329 views36 pages

Network Programming Lab Report

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
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

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

Common questions

Powered by AI

Use the `URLConnection` class. Create a `URL` object and open a connection with `openConnection()`. Fetch the header fields with `getHeaderFields()`, which provides a map of headers; iterate over this map to print each header and its corresponding value. To read content from the connection, wrap the input stream with `InputStreamReader` and `BufferedReader`, then read line by line. Handle exceptions accordingly .

Using the `URL` class, you can extract several components from a URL string, such as the protocol with `getProtocol()`, host with `getHost()`, default port with `getDefaultPort()`, query string with `getQuery()`, path with `getPath()`, file name with `getFile()`, and reference with `getRef()`. Methods are called on a `URL` object which is created by passing the URL string to the `URL` constructor, handling any potential `MalformedURLException` .

Create a `DatagramSocket` for both client and server. On the client-side, convert the message to bytes, then send it using `DatagramPacket` and `send()` on the client's socket directed to the server's address and port. On the server-side, receive the packet with a buffer and `DatagramPacket`, then reconstruct the message. Server sockets listen on a specified port, awaiting packets. Proper exception handling is essential for robust communication .

Use `URLEncoder.encode()` to encode a URL string by specifying the string to encode and a character encoding like 'UTF-8'. Decoding is done with `URLDecoder.decode()` using the encoded string and the same charset. Wrap calls in a try-catch block to handle `UnsupportedEncodingException` in case the specified encoding is not supported .

First, create a `CookieManager` with a default `CookieStore` and set a policy using `CookiePolicy.ACCEPT_ALL`. Retrieve the `CookieStore` from it with `getCookieStore()`. Add cookies using the `add()` method of `CookieStore`, passing a URI and `HttpCookie` instance. To remove cookies, use the `remove()` method. Retrieve cookies using `get()` method with a URI, and configure `HttpCookie` attributes like domain and path as needed .

You can use the `InetAddress` class in Java. First, obtain an `InetAddress` instance using `InetAddress.getByName()` by providing the IP address as a string. Then, use methods like `isLoopbackAddress()`, `isSiteLocalAddress()`, `isMulticastAddress()`, and `isAnyLocalAddress()` on the `InetAddress` instance to check each type. If none of these methods return true, the IP is considered a public/global address. Wrap your code logic in a try-catch block to handle any potential `UnknownHostException` .

Create two URL objects, one with the base URL and another by resolving the relative URL against the base using the `URL` constructor that takes both. Use `toString()` on the `URL` objects to print the base URL, relative URL, and resolved URL. This demonstrates the ability to construct a new `URL` by specifying the `baseUrl` and `relativeUrl` strings and resolving them .

Create a `Socket` object with server's IP and port. Use `BufferedReader` to read the server's input stream. Employ a `while` loop to read lines until there's no more data (`null`). Finally, close the socket to free resources. Proper error handling with try-catch blocks is essential to manage IO exceptions .

You can use the `InetAddress` class in Java. First, you obtain the local host `InetAddress` instance using `InetAddress.getLocalHost()`. Then, you can get the host name with `getHostName()` and the IP address with `getHostAddress()`. Handle `UnknownHostException` to catch errors if the local host name or address cannot be determined .

Create a `Socket` object to connect to the server. Use `PrintWriter` for writing data through the socket's output stream. Simultaneously, use `BufferedReader` to read user input to send data to the server. After data transmission, close the socket. Ensure to handle IO exceptions and manage resources using try-with-resources or try-finally .

You might also like