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

Networking

BCA 6th sem - Networking Lab Report

Uploaded by

Prijan Khad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views

Networking

BCA 6th sem - Networking Lab Report

Uploaded by

Prijan Khad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

1. Write a program that prints the address of www.tufohss.edu.

np

Code

import java.net.*;

public class AddressDemo {

public static void main(String[] args) {

try {

InetAddress address = InetAddress.getByName("www.tufohss.edu.np");

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

System.out.println("IP Address: " + address.getHostAddress());

} catch (UnknownHostException ex) {

System.out.println("Could not find.");

Output
2. Write a program that finds the address of the local machine.

Code

import java.net.*;

public class MyAddress {

public static void main(String[] args) {

try {

InetAddress address = InetAddress.getLocalHost();

System.out.println(address);

} catch (UnknownHostException ex) {

System.out.println("Could not find this computer's address.");

Output
3. Write a program that finds the canonical hostname of a given the
address.

Code

import java.net.*;

public class ReverseTest {

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

InetAddress ia = InetAddress.getByName("182.93.84.136");

System.out.println(ia.getCanonicalHostName());

Output
4. Write a program that lists all the network interfaces.
Code

import java.net.*;

import java.util.*;

public class InterfaceLister {

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

Enumeration<NetworkInterface> interfaces =
NetworkInterface.getNetworkInterfaces();

while (interfaces.hasMoreElements()) {

NetworkInterface ni = interfaces.nextElement();

System.out.println(ni);

Output
5. Write a program to check remote is reachable or not [Testing
Reachability].
Code

import java.net.*;

public class TestingReachabilityEx {

public static void main(String[] args) {

try {

InetAddress net = InetAddress.getByName("22.22.22.22");

if (net.isReachable(100)) {

System.out.println("Success");

} else {

System.out.println("Failed");

} catch (Exception e) {

// Handle any exceptions here

e.printStackTrace();

Output
6. Write a program to demonstrate the SpamCheck.

Code

import java.net.*;

public class SpamCheck { // Corrected the class name to start with an uppercase
letter

public static final String BLACKHOLE = "sbl.spamhaus.org";

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


Added missing square brackets and corrected spacing

try {

InetAddress address = InetAddress.getByName("202.15.5.111"); //


Corrected the IP address format

byte[] quad = address.getAddress();

String query = BLACKHOLE;

for (byte octet : quad) {

int unsignedByte = octet < 0 ? octet + 256 : octet;

query = unsignedByte + "." + query;

// Now, query is something like "202.15.5.111.sbl.spamhaus.org"

InetAddress.getByName(query); // This line doesn't do anything useful


System.out.println("No Spam");

} catch (Exception e) {

System.out.println("Spam");

private static boolean isSpammer(String arg) {

try {

InetAddress address = InetAddress.getByName(arg);

byte[] quad = address.getAddress();

String query = BLACKHOLE;

for (byte octet : quad) {

int unsignedByte = octet < 0 ? octet + 256 : octet;

query = unsignedByte + "." + query;

InetAddress.getByName(query); // This line doesn't do anything useful

return true;

} catch (UnknownHostException e) {

return false;

}
Output
7. Write a program to checks the which protocols does a virtual
machine support or not?

Code

import java.net.*;

public class ProtocolTester {

public static void main(String[] args) {

// Hypertext Transfer Protocol

testProtocol("http://www.adc.org");

// Secure Hypertext Transfer Protocol (HTTPS)

testProtocol("https://www.amazon.com/exec/obidos/order2/");

// File Transfer Protocol

testProtocol("ftp://ibiblio.org/pub/languages/java/javafaq");

// Simple Mail Transfer Protocol

testProtocol("mailto:[email protected]");

// Telnet

testProtocol("telnet://dibner.poly.edu/");

// Local File Access

testProtocol("file:///etc/passwd");
// Gopher

testProtocol("gopher://gopher.anc.org.za/");

private static void testProtocol(String url) {

try {

URL u = new URL(url);

System.out.println(u.getProtocol() + " is supported");

} catch (MalformedURLException ex) {

String protocol = url.substring(0, url.indexOf(':'));

System.out.println(protocol + " is not supported");

Output
8. Write a program for resolving relatives URI.
Code

import java.net.URI;

public class ResolveURL {

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

// Corrected the URIs and removed extra single quotes

String uriBase = "https://www.test.org/";

String uriRelative = "languages/../java";

// Use the URI class constructor with proper names

URI uriBaseURI = new URI(uriBase);

System.out.println("Base URI = " + uriBaseURI.toString());

URI uriRelativeURI = new URI(uriRelative);

System.out.println("Relative URI = " + uriRelativeURI.toString());

// Resolve the relative URI against the base URI

URI uriResolved = uriBaseURI.resolve(uriRelativeURI);

System.out.println("Resolved URI = " + uriResolved.toString());

Output
9. Write a program to implement the CookieStore Methods (add, read,
delete) cookies.

Code

import java.io.*;

import java.net.*;

import java.util.*;

public class CookiesManagerDemo {

public static void main(String[] args) {

CookieManager cookieManager = new CookieManager();

CookieStore cookieStore = cookieManager.getCookieStore();

// Creating cookies and URI

HttpCookie cookieA = new HttpCookie("First", "I");

HttpCookie cookieB = new HttpCookie("Second", "2");

URI uri = URI.create("https://www.ambition.edu.np/");

// Method 1 - add(URI uri, HttpCookie cookie)

cookieStore.add(uri, cookieA);

cookieStore.add(uri, cookieB);

System.out.println("Cookies successfully added\n");

// Method 2 - get(URI uri)

List<HttpCookie> cookiesWithURI = cookieStore.get(uri);


System.out.println("Cookies associated with URI in CookieStore: " +
cookiesWithURI + "\n");

// Method 3 - getCookies()

List<HttpCookie> cookieList = cookieStore.getCookies();

System.out.println("Cookies in CookieStore: " + cookieList + "\n");

// Method 4 - getURIs()

List<URI> uriList = cookieStore.getURIs();

System.out.println("URIs in CookieStore: " + uriList + "\n");

// Method 5 - remove(URI uri, HttpCookie cookie)

System.out.println("Removal of Cookie: " + cookieStore.remove(uri,


cookieA));

List<HttpCookie> remainingCookieList = cookieStore.get(uri);

System.out.println("Remaining Cookies: " + remainingCookieList + "\n");

// Method 6 - removeAll()

System.out.println("Removal of all Cookies: " + cookieStore.removeAll());

List<HttpCookie> emptyCookieList = cookieStore.getCookies();

System.out.println("Empty CookieStore: " + emptyCookieList);

}
Output
10. Write a program to download a web page by using
URLConnection.

Code

import java.io.*;

import java.net.*;

public class SourceViewer {

public static void main(String[] args) {

try {

// Open the URL connection for reading

URL u = new URL("https://www.bing.com/"); // Corrected the URL


syntax

URLConnection uc = u.openConnection();

// Open an input stream to read the content

InputStream stream = uc.getInputStream();

BufferedReader reader = new BufferedReader(new


InputStreamReader(stream));

int c;

while ((c = reader.read()) != -1) { // Corrected the end of file condition

System.out.print((char) c);

// Close the reader


reader.close();

} catch (IOException ex) {

System.err.println(ex);

Output
11. Write a program to print the entire HTTP header.

Code

import java.io.*;

import java.net.*;

public class AllHeaders {

public static void main(String[] args) {

try {

URL u = new URL("https://tufohss.edu.np");

URLConnection uc = u.openConnection();

for (int j = 0;; j++) {

String header = uc.getHeaderField(j);

String headerKey = uc.getHeaderFieldKey(j);

if (header == null) {

break;

if (headerKey == null) {

// This is the first line of the response

System.out.println("Status Line: " + header);


} else {

System.out.println(headerKey + ": " + header);

} catch (MalformedURLException ex) {

System.err.println("It's not a URL I understand.");

} catch (IOException ex) {

System.err.println(ex);

Output
12. Write a program for HTTP request method.

Code

import java.io.*;

import java.net.*;

import java.util.*;

public class LastModified {

public static void main(String[] args) {

try {

URL u = new URL("https://tufohss.edu.np/");

HttpURLConnection http = (HttpURLConnection) u.openConnection();

http.setRequestMethod("HEAD");

System.out.println(u + " was last modified at " + new


Date(http.getLastModified()));

} catch (MalformedURLException ex) {

System.err.println("It is not a URL I understand.");

} catch (IOException ex) {

System.err.println(ex);

System.out.println();

}
Output
12. Write a program to print the URL or URL Connection to
“hafoss.edu.np”.
Code

import java.io.*;

import java.net.*;

public class URLPrinter {

public static void main(String[] args) {

try {

URL u = new URL("http://www.tufohss.edu.np/");

URLConnection uc = u.openConnection();

System.out.println(uc.getURL());

} catch (MalformedURLException ex) {

System.err.println("Malformed URL: " + ex.getMessage());

} catch (IOException ex) {

System.err.println(ex);

Output
13. Write a program socket to client.

Code
import java.net.*;
import java.io.*;
public class ClientChat {
public static void main(String[] args) {
try {
Socket s = new Socket("127.0.0.1", 8888);
System.out.println("Server Connected : " + s);

DataInputStream din = new


DataInputStream(s.getInputStream());
DataOutputStream dout = new
DataOutputStream(s.getOutputStream());

BufferedReader br = new BufferedReader(new


InputStreamReader(System.in));
String str;

do {
str = br.readLine();
dout.writeUTF(str);
dout.flush();
System.out.println("Server Message: " + din.readUTF());
} while (!str.equals("stop"));

s.close();
} catch (Exception e) {
System.out.println(e);
}
}
}

Output
14. Write a program for Creating Secure Sockets with tufhoss.edu.np

Code

import java.io.*;

import java.net.*;

import javax.net.ssl.*;

public class SecureSocketEx {

public static void main(String[] args) {

try {

SSLSocketFactory factory = (SSLSocketFactory)


SSLSocketFactory.getDefault();

SSLSocket socket = (SSLSocket) factory.createSocket("tufohss.edu.np",


443);

String[] supported = socket.getSupportedCipherSuites();

socket.setEnabledCipherSuites(supported);

BufferedWriter out = new BufferedWriter(new


OutputStreamWriter(socket.getOutputStream(), "US-ASCII"));

out.write("GET / HTTP/1.1\r\n");

out.write("Host: tufohss.edu.np\r\n");

out.write("\r\n");

out.flush();

// Read all header fields


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

String line;

while (!(line = in.readLine()).equals("")) {

System.out.println(line);

socket.close();

} catch (IOException e) {

e.printStackTrace();

Output
15. Write a program to implement the concept on Data Conversion.

Code

import java.nio.ByteBuffer;

import java.nio.BufferUnderflowException;

public class DataConversionTest {

public static void main(String[] args) {

int capacity = 8;

try {

ByteBuffer bb = ByteBuffer.allocate(capacity);

bb.asIntBuffer()

.put(10)

.put(20);

bb.rewind();

System.out.println("Original ByteBuffer:");

for (int i = 0; i < capacity / 4; i++) {

System.out.print(bb.getInt() + " ");

bb.rewind();

int value = bb.getInt();

System.out.println("\n\nByteValue: " + value);

int value2 = bb.getInt();


System.out.println("Next ByteValue: " + value2);

} catch (BufferUnderflowException e) {

System.out.println("There are fewer than four bytes remaining in this


buffer");

System.out.println("Exception Thrown: " + e);

Output
16. Write a program for UDP Client example.

Code

import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.net.*;

class UDPClient {

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

BufferedReader inFromUser = new BufferedReader(new


InputStreamReader(System.in));

DatagramSocket clientSocket = new DatagramSocket();

InetAddress IPAddress = InetAddress.getByName("localhost");

byte[] sendData;

byte[] receiveData = new byte[1024];

String sentence = inFromUser.readLine();

sendData = sentence.getBytes();

DatagramPacket sendPacket = new DatagramPacket(sendData,


sendData.length, IPAddress, 9876);

clientSocket.send(sendPacket);

DatagramPacket receivePacket = new DatagramPacket(receiveData,


receiveData.length);
clientSocket.receive(receivePacket);

String modifiedSentence = new String(receivePacket.getData(), 0,


receivePacket.getLength());

System.out.println("FROM SERVER: " + modifiedSentence);

clientSocket.close();

Output
17. Write a program for UDP Server example.

Code

import java.net.*;

import java.io.*;

public class UDPServer {

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

DatagramSocket serverSocket = new DatagramSocket(9876);

byte[] receiveData = new byte[1024];

byte[] sendData;

while (true) {

DatagramPacket receivePacket = new DatagramPacket(receiveData,


receiveData.length);

serverSocket.receive(receivePacket);

String sentence = new String(receivePacket.getData(), 0,


receivePacket.getLength());

System.out.println("RECEIVED: " + sentence);

InetAddress IPAddress = receivePacket.getAddress();

int port = receivePacket.getPort();

sendData = sentence.getBytes();

DatagramPacket sendPacket = new DatagramPacket(sendData,


sendData.length, IPAddress, port);

serverSocket.send(sendPacket);

}
}

Output
17. Write a program to verify that you are receiving multicast data at
a particular host.
Code

MultiSocketServer.java

import java.io.IOException;

import java.net.DatagramPacket;

import java.net.DatagramSocket;

import java.net.InetAddress;

import java.net.UnknownHostException;

public class MulticastSocketServer {

final static String INET_ADDR = "224.0.0.3";

final static int PORT = 8888;

public static void main(String[] args) throws UnknownHostException,


InterruptedException {

InetAddress addr = InetAddress.getByName(INET_ADDR);

try (DatagramSocket serverSocket = new DatagramSocket()) {

String msg = "Hello everyone from server.";

DatagramPacket msgPacket = new DatagramPacket(msg.getBytes(),


msg.getBytes().length, addr, PORT);

serverSocket.send(msgPacket);

System.out.println("Server sent packet with msg: " + msg);

} catch (IOException ex) {

ex.printStackTrace();

}
}

MultiSocketClient.java

import java.io.IOException;

import java.net.DatagramPacket;

import java.net.InetAddress;

import java.net.MulticastSocket;

import java.net.UnknownHostException;

public class MulticastSocketClient {

final static String INET_ADDR = "224.0.0.3";

final static int PORT = 8888;

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

InetAddress address = InetAddress.getByName(INET_ADDR);

byte[] buf = new byte[256];

try (MulticastSocket clientSocket = new MulticastSocket(PORT)) {

clientSocket.joinGroup(address); // Join the multicast group

while (true) {

DatagramPacket msgPacket = new DatagramPacket(buf, buf.length);

clientSocket.receive(msgPacket); // Receive a multicast packet


String msg = new String(buf, 0, buf.length);

System.out.println("Socket received msg: " + msg);

} catch (IOException ex) {

ex.printStackTrace();

Output
18. Write a program to add two numbers using RMI.

Code

Hello.java

import java.rmi.Remote;

import java.rmi.RemoteException;

// Creating Remote interface for our application

public interface Hello extends Remote {

int add(int a, int b) throws RemoteException;

ImplExample.java

import java.rmi.RemoteException;

import java.rmi.server.UnicastRemoteObject;

// Implementing the remote interface

public class ImplExample extends UnicastRemoteObject implements Hello {

public ImplExample() throws RemoteException {

super();

// Implementing the interface method

public int add(int x, int y) throws RemoteException {

System.out.println("Sum = " + (x + y));

return x + y;
}

ServerRMI.java

import java.rmi.registry.Registry;

import java.rmi.registry.LocateRegistry;

import java.rmi.RemoteException;

import java.rmi.server.UnicastRemoteObject;

public class Server {

public Server() {}

public static void main(String[] args) {

try {

// Instantiate the implementation class

Hello obj = new ImplExample();

// Exporting the object of the implementation class

Hello skeleton = (Hello) UnicastRemoteObject.exportObject(obj, 0);

// Creating and binding the remote object (stub) in the registry

Registry registry = LocateRegistry.createRegistry(1099); // Use port


1099 by default

registry.bind("RMITest", skeleton);

System.err.println("Server ready");
} catch (Exception e) {

System.err.println("Server exception: " + e.toString());

e.printStackTrace();

ClientRMI.java

import java.rmi.registry.LocateRegistry;

import java.rmi.registry.Registry;

public class ClientRMI {

private ClientRMI() {}

public static void main(String[] args) {

try {

// Getting the RMI registry

Registry registry = LocateRegistry.getRegistry();

// Looking up the remote object by its binding name

Hello stub = (Hello) registry.lookup("RMITest");

// Calling the remote method using the obtained object

int result = stub.add(5, 10);


// Displaying the result

System.out.println("Result from remote method: " + result);

} catch (Exception e) {

System.err.println("Client exception: " + e.toString());

e.printStackTrace();

Output

You might also like