0% found this document useful (0 votes)
34 views27 pages

Network Programming Lab Report

Network programming lab dox

Uploaded by

Watch Anime
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)
34 views27 pages

Network Programming Lab Report

Network programming lab dox

Uploaded by

Watch Anime
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

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

[Link]:

import [Link];

import [Link];

public class NetworkInfo {

public static void main(String[] args) {

try {

InetAddress address = [Link]("[Link]");

[Link]("Hostname: " + [Link]());

[Link]("Host Address: " + [Link]());

[Link]("Port: 80"); // Default port for HTTP

[Link]("Protocol: HTTP");

} catch (UnknownHostException e) {

[Link]();

}
2)Print all the network interfaces available in a machine:
import [Link];

import [Link];

import [Link];

public class NetworkInterfacesList {

public static void main(String[] args) {

try {

Enumeration<NetworkInterface> networks = [Link]();

while ([Link]()) {

NetworkInterface network = [Link]();

[Link]("Name: " + [Link]());

} catch (SocketException e) {

[Link]();

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

import [Link];

import [Link];

import [Link];

import [Link];

public class NetworkInterfaceByAddress {

public static void main(String[] args) {

try {

InetAddress address = [Link]("[Link]");

Enumeration<NetworkInterface> interfaces = [Link]();

while ([Link]()) {

NetworkInterface network = [Link]();

if ([Link]() && [Link]()) {

[Link]("Short Name: " + [Link]());

[Link]("Full Name: " + [Link]());

} catch (Exception e) {

[Link]();

}
4) Print the localhost of a system and get the network interface of
localhost:
import [Link];

import [Link];

import [Link];

import [Link];

public class LocalhostInfo {

public static void main(String[] args) {

try {

InetAddress localhost = [Link]();

[Link]("Localhost: " + [Link]());

Enumeration<NetworkInterface> interfaces = [Link]();

while ([Link]()) {

NetworkInterface network = [Link]();

if ([Link]() && [Link]()) {

[Link]("Network Interface Name: " + [Link]());

} catch (Exception e) {

[Link]();

}
5) Check if a given IP address is marked as a spammer or is legit:
import [Link];

import [Link];

import [Link];

import [Link];

public class IPCheck {

public static void main(String[] args) {

String ip = "[Link]"; // Example IP

String apiUrl = "[Link] + ip; // Placeholder URL

try {

URL url = new URL(apiUrl);

HttpURLConnection connection = (HttpURLConnection) [Link]();

[Link]("GET");

BufferedReader reader = new BufferedReader(new


InputStreamReader([Link]()));

String responseLine;

while ((responseLine = [Link]()) != null) {

[Link](responseLine);

[Link]();

} catch (Exception e) {

[Link]();

}
6) Test whether a URL is reachable through a given network interface
within 2 seconds:
import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class ReachabilityTest {

public static void main(String[] args) {

try {

InetAddress address = [Link]("[Link]");

URL url = new URL("[Link]

HttpURLConnection connection = (HttpURLConnection) [Link]();

[Link](2000); // 2 seconds

[Link]();

[Link]("URL is reachable through the network interface.");

[Link]();

} catch (IOException e) {

[Link]("URL is not reachable within the given time.");

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

import [Link];

import [Link];

public class IPAddressType {

public static void main(String[] args) {

try {

InetAddress address = [Link]("[Link]");

if ([Link]().length == 4) {

[Link]("Address Type: IPv4");

} else {

[Link]("Address Type: IPv6");

} catch (UnknownHostException e) {

[Link]();

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

import [Link];

import [Link];

import [Link];

import [Link];

public class IPAndMACAddress {

public static void main(String[] args) {

try {

Enumeration<NetworkInterface> interfaces = [Link]();

while ([Link]()) {

NetworkInterface network = [Link]();

Enumeration<InetAddress> addresses = [Link]();

while ([Link]()) {

InetAddress address = [Link]();

if (![Link]()) {

[Link]("IP Address: " + [Link]());

byte[] mac = [Link]();

if (mac != null) {

StringBuilder macAddress = new StringBuilder();

for (byte b : mac) {

[Link]([Link]("%02X:", b));

if ([Link]() > 0) {

[Link]([Link]() - 1);

[Link]("MAC Address: " + [Link]());

}
}

} catch (SocketException e) {

[Link]();

}
9) Minimal processing of a web log:

import [Link];

import [Link];

import [Link];

public class WebLogProcessor {

public static void main(String[] args) {

String filePath = "[Link]"; // Path to your web log file

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

String line;

while ((line = [Link]()) != null) {

// Basic processing: print each line

[Link](line);

} catch (IOException e) {

[Link]();

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

import [Link];

import [Link];

public class URLComponents {

public static void main(String[] args) {

try {

URI uri = new URI("[Link]

[Link]("Scheme: " + [Link]());

[Link]("Authority: " + [Link]());

[Link]("Port: " + [Link]());

[Link]("Path: " + [Link]());

[Link]("Fragment: " + [Link]());

[Link]("Query: " + [Link]());

} catch (URISyntaxException e) {

[Link]();

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

import [Link];

import [Link];

public class URIResolver {

public static void main(String[] args) {

try {

URI baseURI = new URI("[Link]

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

URI resolvedURI = [Link](pathURI);

[Link]("Resolved URI: " + [Link]());

} catch (URISyntaxException e) {

[Link]();

}
12) Encode and decode a string:

import [Link];

import [Link];

import [Link];

public class EncodingDecoding {

public static void main(String[] args) {

try {

String original = "This string has space";

String encoded = [Link](original, "UTF-8");

String decoded = [Link](encoded, "UTF-8");

[Link]("Encoded: " + encoded);

[Link]("Decoded: " + decoded);

} catch (UnsupportedEncodingException e) {

[Link]();

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

import [Link];

import [Link];

import [Link];

public class URLInfo {

public static void main(String[] args) {

try {

URL url = new URL("[Link]

HttpURLConnection connection = (HttpURLConnection) [Link]();

[Link]("GET");

[Link]();

[Link]("Last Modified: " + [Link]("Last-Modified"));

[Link]("Content Length: " + [Link]());

[Link]("Content Type: " + [Link]());

[Link]();

} catch (IOException e) {

[Link]();

}
14) Create cookies for [Link] and store them in a cookie store:

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class CookieExample {

public static void main(String[] args) {

try {

URL url = new URL("[Link]

HttpURLConnection connection = (HttpURLConnection) [Link]();

[Link]("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 = [Link]();

[Link]([Link](), cookie1);

[Link]([Link](), cookie2);

// Print cookies

List<HttpCookie> cookies = [Link]([Link]());

for (HttpCookie cookie : cookies) {


[Link]("Cookie: " + cookie);

[Link]();

} catch (Exception e) {

[Link]();

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

import [Link];

import [Link];

import [Link];

import [Link];

public class HTTPHeaders {

public static void main(String[] args) {

try {

URL url = new URL("[Link]

HttpURLConnection connection = (HttpURLConnection) [Link]();

[Link]("GET");

[Link]();

Map<String, List<String>> headers = [Link]();

for ([Link]<String, List<String>> entry : [Link]()) {

[Link]("Header: " + [Link]() + " Values: " + [Link]());

}
[Link]();

} catch (IOException e) {

[Link]();

16)Download a web page through a proxy connection:

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class ProxyDownload {

public static void main(String[] args) {

try {

Proxy proxy = new Proxy([Link], new InetSocketAddress("[Link]", 8080));

URL url = new URL("[Link]

HttpURLConnection connection = (HttpURLConnection) [Link](proxy);

BufferedReader reader = new BufferedReader(new


InputStreamReader([Link]()));

String line;

while ((line = [Link]()) != null) {

[Link](line);

[Link]();

[Link]();

} catch (IOException e) {
[Link]();

}
17) Read from a socket:
import [Link];

import [Link];

import [Link];

import [Link];

public class SocketReader {

public static void main(String[] args) {

try (ServerSocket serverSocket = new ServerSocket(12345);

Socket clientSocket = [Link]();

BufferedReader in = new BufferedReader(new


InputStreamReader([Link]()))) {

String line;

while ((line = [Link]()) != null) {

[Link]("Received: " + line);

} catch (IOException e) {

[Link]();

}
18) Create a server socket and print a log message when a client connects:
import [Link];

import [Link];

import [Link];

public class ServerSocketExample {

public static void main(String[] args) {

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

[Link]("Server is running and waiting for connections...");

while (true) {

Socket clientSocket = [Link]();

[Link]("New client connected: " + [Link]());

} catch (IOException e) {

[Link]();

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

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class DaytimeServer {

public static void main(String[] args) {

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

[Link]("Daytime Server is running...");

while (true) {

Socket clientSocket = [Link]();

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

} catch (IOException e) {

[Link]();

class DaytimeHandler implements Runnable {

private Socket socket;

DaytimeHandler(Socket socket) {

[Link] = socket;

}
@Override

public void run() {

try (BufferedWriter out = new BufferedWriter(new


OutputStreamWriter([Link]()))) {

[Link]("Current time: " + [Link]().toString() + "\n");

[Link]();

} catch (IOException e) {

[Link]();

Client:

import [Link];

import [Link];

import [Link];

import [Link];

public class DaytimeClient {

public static void main(String[] args) {

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

BufferedReader in = new BufferedReader(new InputStreamReader([Link]()))) {

String response = [Link]();

[Link]("Server response: " + response);

} catch (IOException e) {

[Link]();

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

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class ThreadPoolDaytimeServer {

private static final int PORT = 12345;

private static final int POOL_SIZE = 50;

public static void main(String[] args) {

ExecutorService pool = [Link](POOL_SIZE);

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

[Link]("Daytime Server with Thread Pool is running...");

while (true) {

Socket clientSocket = [Link]();

[Link](new DaytimeHandler(clientSocket));

} catch (IOException e) {

[Link]();

} finally {

[Link]();

}
}

class DaytimeHandler implements Runnable {

private Socket socket;

DaytimeHandler(Socket socket) {

[Link] = socket;

@Override

public void run() {

try (BufferedWriter out = new BufferedWriter(new


OutputStreamWriter([Link]()))) {

[Link]("Current time: " + [Link]().toString() + "\n");

[Link]();

} catch (IOException e) {

[Link]();

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

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class SecureClient {

public static void main(String[] args) {


try {

SSLSocketFactory factory = (SSLSocketFactory) [Link]();

SSLSocket socket = (SSLSocket) [Link]("[Link]", 443);

BufferedReader in = new BufferedReader(new InputStreamReader([Link]()));

String line;

while ((line = [Link]()) != null) {

[Link](line);

[Link]();

[Link]();

} catch (IOException e) {

[Link]();

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

import [Link];

import [Link];

import [Link];

import [Link];

public class UDPClient {

public static void main(String[] args) {

try (DatagramSocket socket = new DatagramSocket()) {

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

DatagramPacket sendPacket = new DatagramPacket(sendData, [Link],


[Link]("localhost"), 9876);

[Link](sendPacket);

byte[] receiveData = new byte[1024];

DatagramPacket receivePacket = new DatagramPacket(receiveData, [Link]);

[Link](receivePacket);

String received = new String([Link](), 0, [Link]());

[Link]("Received from server: " + received);

} catch (IOException e) {

[Link]();

Server:

import [Link];
import [Link];

import [Link];

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, [Link]);

[Link](receivePacket);

String message = new String([Link](), 0, [Link]());

[Link]("Received from client: " + message);

DatagramPacket sendPacket = new DatagramPacket(receiveData, [Link],


[Link](), [Link]());

[Link](sendPacket);

} catch (IOException e) {

[Link]();

Common questions

Powered by AI

Java supports URL and URI handling using classes like URI and utilities such as URLEncoder and URLDecoder to process strings. Encoding and decoding ensure data is safely transmitted over HTTP, while URI resolution combines base URIs with paths to form absolute URLs, facilitating dynamic web interactions and constructing links between resources .

In Java, the determination of whether an IP address is IPv4 or IPv6 can be made by examining the byte length of the address obtained via the InetAddress class. An IPv4 address has a length of 4 bytes, while an IPv6 address has a length of 16 bytes. Practical implications of this distinction include differences in address space (IPv6 has a vastly larger address space), use cases (IPv6 is more suited for modern networking needs due to its additional features like auto-configuration and improved routing), and potential compatibility issues due to networks still largely being IPv4-centric .

Java can download a web page through a proxy connection by creating a Proxy object with the appropriate type and address, and using it within an HttpURLConnection setup. Potential security concerns include the risk of exposing sensitive information to the proxy server, susceptibility to man-in-the-middle attacks, and ensuring that the proxy is properly secured and trusted .

To check if a given IP address is legit or marked as spam in Java, you typically connect to an external API using an HttpURLConnection, construct the URL using the target IP, perform a GET request, and parse the response to determine the IP status. This functionality is crucial for network security as it helps in filtering and preventing access from malicious IPs, protecting systems from spam and potential breaches .

Java can test the reachability of a URL through a specific network interface by opening an HttpURLConnection and setting a connect timeout (e.g., 2000 milliseconds). Challenges in this process include handling network latency or connectivity issues, managing exceptions due to unreachable URLs, and ensuring the network interface is correctly specified and operational during the test .

The benefits of using a thread pool for a multithreaded server in Java include efficient resource management, reduced overhead from frequent thread creation, and improved responsiveness. However, risks involve the potential for deadlock if improperly managed, overloading the server with excessive concurrent tasks, and difficulty in debugging concurrency issues .

The NetworkInterface class in Java networking provides methods to interact with and analyze the machine's network interfaces. It facilitates network programming tasks by allowing enumeration of network interfaces, retrieval of interface attributes such as name and addresses, and supporting the implementation of network protocols. It is essential for managing network resources and optimizing connectivity .

Java handles printing IP and MAC addresses by iterating over NetworkInterface elements and retrieving InetAddresses associated with each. It uses getHardwareAddress to retrieve the MAC address, which is then formatted for printing. This capability is significant for network diagnostics and troubleshooting, allowing system administrators to verify interface configurations and network connectivity .

Java's Socket class enables server-client communication by establishing channels through which data can be sent and received. When using it for multithreaded applications, considerations include ensuring thread safety, managing concurrency to avoid race conditions, and efficiently handling multiple connections by employing thread pools to balance load and improve performance .

To print hostname, host address, port, and protocol of a URL in Java, you use the InetAddress class to get the hostname and address, and typically set the default HTTP port to 80 with the protocol HTTP. This can be done using getByName for hostname and host address, and hardcoding the port and protocol as needed. This process is relevant in network programming for tasks such as debugging or configuring network applications, where understanding the specifics of the connection setup is necessary .

You might also like