Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
1 views

Network Programming LAB REPORT

Network programming lab dox

Uploaded by

Watch Anime
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Network Programming LAB REPORT

Network programming lab dox

Uploaded by

Watch Anime
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

1) Print the hostname, host address, port, and protocol of

www.google.com:

import java.net.InetAddress;

import java.net.UnknownHostException;

public class NetworkInfo {

public static void main(String[] args) {

try {

InetAddress address = InetAddress.getByName("www.google.com");

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

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

System.out.println("Port: 80"); // Default port for HTTP

System.out.println("Protocol: HTTP");

} catch (UnknownHostException e) {

e.printStackTrace();

}
2)Print all the network interfaces available in a machine:
import java.net.NetworkInterface;

import java.net.SocketException;

import java.util.Enumeration;

public class NetworkInterfacesList {

public static void main(String[] args) {

try {

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

while (networks.hasMoreElements()) {

NetworkInterface network = networks.nextElement();

System.out.println("Name: " + network.getName());

} catch (SocketException e) {

e.printStackTrace();

}
3) Get the network interface associated with 127.0.0.1 and print its short and full name:

import java.net.InetAddress;

import java.net.NetworkInterface;

import java.net.SocketException;

import java.util.Enumeration;

public class NetworkInterfaceByAddress {

public static void main(String[] args) {

try {

InetAddress address = InetAddress.getByName("127.0.0.1");

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

while (interfaces.hasMoreElements()) {

NetworkInterface network = interfaces.nextElement();

if (network.isLoopback() && network.isUp()) {

System.out.println("Short Name: " + network.getName());

System.out.println("Full Name: " + network.getDisplayName());

} catch (Exception e) {

e.printStackTrace();

}
4) Print the localhost of a system and get the network interface of
localhost:
import java.net.InetAddress;

import java.net.NetworkInterface;

import java.net.SocketException;

import java.util.Enumeration;

public class LocalhostInfo {

public static void main(String[] args) {

try {

InetAddress localhost = InetAddress.getLocalHost();

System.out.println("Localhost: " + localhost.getHostName());

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

while (interfaces.hasMoreElements()) {

NetworkInterface network = interfaces.nextElement();

if (network.isLoopback() && network.isUp()) {

System.out.println("Network Interface Name: " + network.getName());

} catch (Exception e) {

e.printStackTrace();

}
5) Check if a given IP address is marked as a spammer or is legit:
import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.net.HttpURLConnection;

import java.net.URL;

public class IPCheck {

public static void main(String[] args) {

String ip = "8.8.8.8"; // Example IP

String apiUrl = "https://api.ipcheck.com/" + ip; // Placeholder URL

try {

URL url = new URL(apiUrl);

HttpURLConnection connection = (HttpURLConnection) url.openConnection();

connection.setRequestMethod("GET");

BufferedReader reader = new BufferedReader(new


InputStreamReader(connection.getInputStream()));

String responseLine;

while ((responseLine = reader.readLine()) != null) {

System.out.println(responseLine);

reader.close();

} catch (Exception e) {

e.printStackTrace();

}
6) Test whether a URL is reachable through a given network interface
within 2 seconds:
import java.io.IOException;

import java.net.HttpURLConnection;

import java.net.InetAddress;

import java.net.NetworkInterface;

import java.net.URL;

import java.util.Enumeration;

public class ReachabilityTest {

public static void main(String[] args) {

try {

InetAddress address = InetAddress.getByName("example.com");

URL url = new URL("http://example.com");

HttpURLConnection connection = (HttpURLConnection) url.openConnection();

connection.setConnectTimeout(2000); // 2 seconds

connection.connect();

System.out.println("URL is reachable through the network interface.");

connection.disconnect();

} catch (IOException e) {

System.out.println("URL is not reachable within the given time.");

}
7) Check if an IP address is IPv4 or IPv6:

import java.net.InetAddress;

import java.net.UnknownHostException;

public class IPAddressType {

public static void main(String[] args) {

try {

InetAddress address = InetAddress.getByName("255.234.180.23");

if (address.getAddress().length == 4) {

System.out.println("Address Type: IPv4");

} else {

System.out.println("Address Type: IPv6");

} catch (UnknownHostException e) {

e.printStackTrace();

}
8) Print the IP address and MAC address of any system:

import java.net.InetAddress;

import java.net.NetworkInterface;

import java.net.SocketException;

import java.util.Enumeration;

public class IPAndMACAddress {

public static void main(String[] args) {

try {

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

while (interfaces.hasMoreElements()) {

NetworkInterface network = interfaces.nextElement();

Enumeration<InetAddress> addresses = network.getInetAddresses();

while (addresses.hasMoreElements()) {

InetAddress address = addresses.nextElement();

if (!address.isLoopbackAddress()) {

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

byte[] mac = network.getHardwareAddress();

if (mac != null) {

StringBuilder macAddress = new StringBuilder();

for (byte b : mac) {

macAddress.append(String.format("%02X:", b));

if (macAddress.length() > 0) {

macAddress.deleteCharAt(macAddress.length() - 1);

System.out.println("MAC Address: " + macAddress.toString());

}
}

} catch (SocketException e) {

e.printStackTrace();

}
9) Minimal processing of a web log:

import java.io.BufferedReader;

import java.io.FileReader;

import java.io.IOException;

public class WebLogProcessor {

public static void main(String[] args) {

String filePath = "web.log"; // Path to your web log file

try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {

String line;

while ((line = reader.readLine()) != null) {

// Basic processing: print each line

System.out.println(line);

} catch (IOException e) {

e.printStackTrace();

}
10) Print scheme, authority, port, path, section, and query string of a URL:

import java.net.URI;

import java.net.URISyntaxException;

public class URLComponents {

public static void main(String[] args) {

try {

URI uri = new URI("http://example.com:7880/en/4.2/querysets/?q=query#queryset-api");

System.out.println("Scheme: " + uri.getScheme());

System.out.println("Authority: " + uri.getAuthority());

System.out.println("Port: " + uri.getPort());

System.out.println("Path: " + uri.getPath());

System.out.println("Fragment: " + uri.getFragment());

System.out.println("Query: " + uri.getQuery());

} catch (URISyntaxException e) {

e.printStackTrace();

}
11) Resolve a URI and a path to form a complete URI:

import java.net.URI;

import java.net.URISyntaxException;

public class URIResolver {

public static void main(String[] args) {

try {

URI baseURI = new URI("http://example.com");

URI pathURI = new URI("colleges/KCT");

URI resolvedURI = baseURI.resolve(pathURI);

System.out.println("Resolved URI: " + resolvedURI.toString());

} catch (URISyntaxException e) {

e.printStackTrace();

}
12) Encode and decode a string:

import java.io.UnsupportedEncodingException;

import java.net.URLEncoder;

import java.net.URLDecoder;

public class EncodingDecoding {

public static void main(String[] args) {

try {

String original = "This string has space";

String encoded = URLEncoder.encode(original, "UTF-8");

String decoded = URLDecoder.decode(encoded, "UTF-8");

System.out.println("Encoded: " + encoded);

System.out.println("Decoded: " + decoded);

} catch (UnsupportedEncodingException e) {

e.printStackTrace();

}
13) Print the last modified date, content length, and content type of a URL:

import java.io.IOException;

import java.net.HttpURLConnection;

import java.net.URL;

public class URLInfo {

public static void main(String[] args) {

try {

URL url = new URL("http://example.com");

HttpURLConnection connection = (HttpURLConnection) url.openConnection();

connection.setRequestMethod("GET");

connection.connect();

System.out.println("Last Modified: " + connection.getHeaderField("Last-Modified"));

System.out.println("Content Length: " + connection.getContentLength());

System.out.println("Content Type: " + connection.getContentType());

connection.disconnect();

} catch (IOException e) {

e.printStackTrace();

}
14) Create cookies for example.com and store them in a cookie store:

import java.io.IOException;

import java.net.HttpURLConnection;

import java.net.URL;

import java.net.HttpCookie;

import java.net.CookieManager;

import java.net.CookieStore;

import java.util.List;

public class CookieExample {

public static void main(String[] args) {

try {

URL url = new URL("http://example.com");

HttpURLConnection connection = (HttpURLConnection) url.openConnection();

connection.setRequestMethod("GET");

// Create cookies

HttpCookie cookie1 = new HttpCookie("cookieName1", "cookieValue1");

HttpCookie cookie2 = new HttpCookie("cookieName2", "cookieValue2");

// Store cookies in a cookie manager

CookieManager cookieManager = new CookieManager();

CookieStore cookieStore = cookieManager.getCookieStore();

cookieStore.add(url.toURI(), cookie1);

cookieStore.add(url.toURI(), cookie2);

// Print cookies

List<HttpCookie> cookies = cookieStore.get(url.toURI());

for (HttpCookie cookie : cookies) {


System.out.println("Cookie: " + cookie);

connection.disconnect();

} catch (Exception e) {

e.printStackTrace();

15) Print all headers and their values from an HTTP response:

import java.io.IOException;

import java.net.HttpURLConnection;

import java.net.URL;

import java.util.Map;

public class HTTPHeaders {

public static void main(String[] args) {

try {

URL url = new URL("http://example.com");

HttpURLConnection connection = (HttpURLConnection) url.openConnection();

connection.setRequestMethod("GET");

connection.connect();

Map<String, List<String>> headers = connection.getHeaderFields();

for (Map.Entry<String, List<String>> entry : headers.entrySet()) {

System.out.println("Header: " + entry.getKey() + " Values: " + entry.getValue());

}
connection.disconnect();

} catch (IOException e) {

e.printStackTrace();

16)Download a web page through a proxy connection:

import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.net.HttpURLConnection;

import java.net.InetSocketAddress;

import java.net.Proxy;

import java.net.URL;

public class ProxyDownload {

public static void main(String[] args) {

try {

Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy.example.com", 8080));

URL url = new URL("http://example.com");

HttpURLConnection connection = (HttpURLConnection) url.openConnection(proxy);

BufferedReader reader = new BufferedReader(new


InputStreamReader(connection.getInputStream()));

String line;

while ((line = reader.readLine()) != null) {

System.out.println(line);

reader.close();

connection.disconnect();

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

}
17) Read from a socket:
import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.net.ServerSocket;

import java.net.Socket;

public class SocketReader {

public static void main(String[] args) {

try (ServerSocket serverSocket = new ServerSocket(12345);

Socket clientSocket = serverSocket.accept();

BufferedReader in = new BufferedReader(new


InputStreamReader(clientSocket.getInputStream()))) {

String line;

while ((line = in.readLine()) != null) {

System.out.println("Received: " + line);

} catch (IOException e) {

e.printStackTrace();

}
18) Create a server socket and print a log message when a client connects:
import java.io.IOException;

import java.net.ServerSocket;

import java.net.Socket;

public class ServerSocketExample {

public static void main(String[] args) {

try (ServerSocket serverSocket = new ServerSocket(12345)) {

System.out.println("Server is running and waiting for connections...");

while (true) {

Socket clientSocket = serverSocket.accept();

System.out.println("New client connected: " + clientSocket.getInetAddress());

} catch (IOException e) {

e.printStackTrace();

}
19) Multithreaded client-server program for daytime service:
Server:

import java.io.BufferedWriter;

import java.io.OutputStreamWriter;

import java.io.IOException;

import java.net.ServerSocket;

import java.net.Socket;

public class DaytimeServer {

public static void main(String[] args) {

try (ServerSocket serverSocket = new ServerSocket(12345)) {

System.out.println("Daytime Server is running...");

while (true) {

Socket clientSocket = serverSocket.accept();

new Thread(new DaytimeHandler(clientSocket)).start();

} catch (IOException e) {

e.printStackTrace();

class DaytimeHandler implements Runnable {

private Socket socket;

DaytimeHandler(Socket socket) {

this.socket = socket;

}
@Override

public void run() {

try (BufferedWriter out = new BufferedWriter(new


OutputStreamWriter(socket.getOutputStream()))) {

out.write("Current time: " + java.time.LocalTime.now().toString() + "\n");

out.flush();

} catch (IOException e) {

e.printStackTrace();

Client:

import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.io.IOException;

import java.net.Socket;

public class DaytimeClient {

public static void main(String[] args) {

try (Socket socket = new Socket("localhost", 12345);

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

String response = in.readLine();

System.out.println("Server response: " + response);

} catch (IOException e) {

e.printStackTrace();

}
20) Multithreaded client-server program for daytime service with a thread
pool of 50:
Server:

import java.io.BufferedWriter;

import java.io.OutputStreamWriter;

import java.io.IOException;

import java.net.ServerSocket;

import java.net.Socket;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

public class ThreadPoolDaytimeServer {

private static final int PORT = 12345;

private static final int POOL_SIZE = 50;

public static void main(String[] args) {

ExecutorService pool = Executors.newFixedThreadPool(POOL_SIZE);

try (ServerSocket serverSocket = new ServerSocket(PORT)) {

System.out.println("Daytime Server with Thread Pool is running...");

while (true) {

Socket clientSocket = serverSocket.accept();

pool.execute(new DaytimeHandler(clientSocket));

} catch (IOException e) {

e.printStackTrace();

} finally {

pool.shutdown();

}
}

class DaytimeHandler implements Runnable {

private Socket socket;

DaytimeHandler(Socket socket) {

this.socket = socket;

@Override

public void run() {

try (BufferedWriter out = new BufferedWriter(new


OutputStreamWriter(socket.getOutputStream()))) {

out.write("Current time: " + java.time.LocalTime.now().toString() + "\n");

out.flush();

} catch (IOException e) {

e.printStackTrace();

21) Create a secure client socket to read from a secure server socket:

import javax.net.ssl.SSLSocket;

import javax.net.ssl.SSLSocketFactory;

import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.io.IOException;

public class SecureClient {

public static void main(String[] args) {


try {

SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();

SSLSocket socket = (SSLSocket) factory.createSocket("secure.example.com", 443);

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

String line;

while ((line = in.readLine()) != null) {

System.out.println(line);

in.close();

socket.close();

} catch (IOException e) {

e.printStackTrace();

}
22) Create a UDP client-socket echo program:
Client:

import java.io.IOException;

import java.net.DatagramPacket;

import java.net.DatagramSocket;

import java.net.InetAddress;

public class UDPClient {

public static void main(String[] args) {

try (DatagramSocket socket = new DatagramSocket()) {

byte[] sendData = "Hello, Server".getBytes();

DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,


InetAddress.getByName("localhost"), 9876);

socket.send(sendPacket);

byte[] receiveData = new byte[1024];

DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

socket.receive(receivePacket);

String received = new String(receivePacket.getData(), 0, receivePacket.getLength());

System.out.println("Received from server: " + received);

} catch (IOException e) {

e.printStackTrace();

Server:

import java.io.IOException;
import java.net.DatagramPacket;

import java.net.DatagramSocket;

public class UDPServer {

public static void main(String[] args) {

try (DatagramSocket socket = new DatagramSocket(9876)) {

byte[] receiveData = new byte[1024];

DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

socket.receive(receivePacket);

String message = new String(receivePacket.getData(), 0, receivePacket.getLength());

System.out.println("Received from client: " + message);

DatagramPacket sendPacket = new DatagramPacket(receiveData, receiveData.length,


receivePacket.getAddress(), receivePacket.getPort());

socket.send(sendPacket);

} catch (IOException e) {

e.printStackTrace();

You might also like