0% found this document useful (0 votes)
3 views23 pages

Network Programming

The document explains the client-server software model, where clients request services from servers. It highlights Java's features for network programming, including platform independence, rich libraries, support for protocols, multithreading, and built-in security. Additionally, it covers the use of classes like NetworkInterface and InetAddress, HTTP methods, and the strengths and weaknesses of Java in network programming.

Uploaded by

Kajal Gotame
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)
3 views23 pages

Network Programming

The document explains the client-server software model, where clients request services from servers. It highlights Java's features for network programming, including platform independence, rich libraries, support for protocols, multithreading, and built-in security. Additionally, it covers the use of classes like NetworkInterface and InetAddress, HTTP methods, and the strengths and weaknesses of Java in network programming.

Uploaded by

Kajal Gotame
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

1. Define client server software model.

explain the features of java as a network


programming

Client-Server Software Model: The Client-Server model is a distributed application


structure that partitions tasks or workloads between service providers (servers) and service
requesters (clients).

 Client: A system that sends requests for services or resources.


 Server: A system that provides services or resources to clients upon request.

Features of Java as a Network Programming Language:

Java provides strong support for network programming, making it ideal for developing
distributed systems and internet-based applications.

Key Features:

1. Platform Independence:
o Java programs run on any device with a Java Virtual Machine (JVM), making
them portable across systems.
2. Rich Library ([Link] package):
o Java provides high-level classes and interfaces such as Socket,
ServerSocket, InetAddress, URL, and URLConnection for easy
network programming.
3. Support for Protocols:
o Java supports many standard network protocols like TCP, UDP, HTTP, FTP, etc.
4. Multithreading:
o Java supports multithreading, enabling efficient handling of multiple client
requests concurrently.
5. Built-in Security:
o Java provides a secure execution environment through features like the Security
Manager, sandboxing, and cryptographic APIs.
6. Object Serialization:
o Java allows objects to be converted into byte streams, making it easier to transmit
data over a network (especially in RMI).
7. Support for Distributed Computing:
o Technologies like Java RMI (Remote Method Invocation) and CORBA allow
distributed object communication.
8. Ease of Use:
Java abstracts many low-level networking details, making it easier to develop robust
network applications.
2. what is the use of Networkinterface class? Explain the basic features of
NetworkINterface class.

The NetworkInterface class in Java (part of the [Link] package) represents a network interface
on the local machine. This class provides methods to retrieve details about the machine’s
network interfaces, such as IP addresses, MAC addresses, and interface status.

It is particularly useful when:

 You want to list or access local network hardware (like Ethernet or Wi-Fi interfaces).
 You want to get the IP addresses or MAC address of your computer.
 You are working with advanced networking applications that need to bind to specific
interfaces.

Basic Features of NetworkInterface Class:

Here are the key features and functionalities:

1. Listing All Network Interfaces:


o Use [Link]() to retrieve all available network
interfaces on the machine.

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

2. Getting Interface by Name or Address:


o You can get a specific interface by name (eth0, wlan0, etc.) or IP address.

NetworkInterface ni = [Link]("eth0");
NetworkInterface ni2 =
[Link]([Link]());

3. Retrieving IP Addresses:
o You can list all IP addresses associated with an interface.

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

4. Getting MAC Address:


o Retrieve the physical (MAC) address of the network interface.

byte[] mac = [Link]();

5. Checking Interface Properties:


o You can check if the interface is:
Up or down: [Link]()
Loopback: [Link]()
Virtual: [Link]()
Supports multicast: [Link]()
6. Display Name and Index:
o Get the display name and system index of the interface.

String name = [Link]();

int index = [Link]();


3. Explain HTTP methods with example
HTTP (HyperText Transfer Protocol) defines a set of request methods used by clients
(like browsers or applications) to interact with resources on a server.

1. GET

 Purpose: Retrieves data from the server (read-only).


 Used when: You want to fetch or view data.

2. POST

 Purpose: Sends data to the server to create a new resource.


 Used when: Submitting form data, uploading files, etc.

3. PUT

 Purpose: Updates or replaces an existing resource.


 Used when: You want to modify the entire content of a resource.

4. PATCH

 Purpose: Partially updates an existing resource.


 Used when: You want to change only specific fields.

DELETE

 Purpose: Deletes a resource from the server.


 Used when: You want to remove data.

import [Link].*;
import [Link].*;

public class SimpleHttpDemo {

// Simple GET request


public static void sendGET() {
try {
URL url = new URL("[Link]
HttpURLConnection con = (HttpURLConnection) [Link]();
[Link]("GET");

BufferedReader in = new BufferedReader(new


InputStreamReader([Link]()));
String line;
StringBuilder response = new StringBuilder();
while ((line = [Link]()) != null) {
[Link](line);
}
[Link]();

[Link]("GET Response:\n" + response);


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

// Simple POST request


public static void sendPOST() {
try {
URL url = new URL("[Link]
HttpURLConnection con = (HttpURLConnection) [Link]();
[Link]("POST");
[Link]("Content-Type", "application/json; utf-8");
[Link](true);

String json = "{\"title\":\"test\",\"body\":\"This is a post\",\"userId\":1}";

try (OutputStream os = [Link]()) {


byte[] input = [Link]("utf-8");
[Link](input, 0, [Link]);
}

BufferedReader in = new BufferedReader(new


InputStreamReader([Link](), "utf-8"));
String line;
StringBuilder response = new StringBuilder();
while ((line = [Link]()) != null) {
[Link](line);
}
[Link]();

[Link]("POST Response:\n" + response);


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

public static void main(String[] args) {


sendGET();
[Link]("\n---------------------------\n");
sendPOST();
}
}

4. Write a program to display the socket information[address,port,localaddress,localport].


import [Link];
import [Link];

public class SocketInfo {


public static void main(String[] args) {
try {
// Connect to a remote host (like [Link]) on port 80 (HTTP)
Socket socket = new Socket("[Link]", 80);

// Display socket info


[Link]("Remote Address: " + [Link]());
[Link]("Remote Port: " + [Link]());
[Link]("Local Address: " + [Link]());
[Link]("Local Port: " + [Link]());

// Close the socket


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

5. Explain the strengths and weakness of java programming as a network programming


language.
Strengths of Java in Network Programming

1. Rich Built-in Networking API:


o Java provides a complete set of classes in the [Link] package (e.g., Socket,
ServerSocket, URL, HttpURLConnection, DatagramSocket).
o It supports TCP, UDP, multicasting, and HTTP easily.
2. Platform Independence:
o Java’s write once, run anywhere approach allows network programs to run on
any OS with a JVM.
3. High-Level Abstraction:
o Java simplifies complex networking tasks, hiding low-level socket handling
details.
o Easy to implement client-server models with just a few lines of code.
4. Built-in Security Features:
o Java offers SecurityManager, SSL support, and firewall-safe networking.
o Java’s sandboxing ensures that network apps (like applets) don’t harm the system.
5. Multithreading Support:
o Java has strong multithreading capabilities, useful for handling multiple client
connections simultaneously.
6. Standard Library Support:
o Support for HTTP/HTTPS, REST API access, and even newer HttpClient APIs
from Java 11 onwards.
7. Cross-Platform Server Apps:
o Java is widely used in enterprise-grade networking applications (like web servers,
mail servers, and chat servers).

❌ Weaknesses of Java in Network Programming

1. Performance Overhead:
o Java is slower compared to low-level languages like C/C++, especially for high-
performance or real-time networking apps.
2. Verbose Syntax:
o Java code can be quite verbose compared to languages like Python, especially for
basic networking tasks.
3. Limited Low-Level Access:
o Java abstracts a lot of networking details, which limits fine-grained control over
packets and protocols.
4. Garbage Collection Delays:
o Java’s automatic memory management can sometimes cause unpredictable
delays in time-sensitive applications.
5. Complex for Simple Tasks:
o Simple HTTP requests or REST API calls require multiple classes and
configurations (unless using external libraries).
6. Heavier Resource Usage:
o Java applications generally use more memory and CPU than equivalent C-based
applications.

7. What is the use of InetAddress class? Write a program to retrieve IP and MAC address?
The InetAddress class in Java is part of the [Link] package, and it's used for handling IP
addresses. It provides methods to obtain the IP address of a host, its hostname, and to perform
reverse DNS lookups.

Key Features of InetAddress:

 Retrieve Local and Remote IP Addresses: It can be used to get the IP address of the
local machine or any remote host by using the host name or IP address.
 Host Lookup: You can use InetAddress to perform reverse DNS lookups.
 Multicast Address: Supports checking for multicast addresses.
 Methods:
o getLocalHost(): Returns the local host IP address.
o getByName(String host): Resolves the IP address for a given host name.
o getHostAddress(): Returns the string form of the IP address.
o getHostName(): Returns the host name corresponding to the IP address.

import [Link].*;
import [Link];

public class IPandMACAddress {

public static void main(String[] args) {


try {
// Retrieve local IP address using InetAddress
InetAddress localHost = [Link]();
[Link]("IP Address: " + [Link]());

// Retrieve MAC address using NetworkInterface


NetworkInterface networkInterface =
[Link](localHost);
if (networkInterface != null) {
byte[] macAddress = [Link]();
if (macAddress != null) {
[Link]("MAC Address: ");
for (int i = 0; i < [Link]; i++) {
[Link]("%02X", macAddress[i]);
if (i != [Link] - 1) {
[Link]("-");
}
}
[Link]();
} else {
[Link]("MAC Address not found.");
}
} else {
[Link]("Network interface not found.");
}

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

8. Define URL class. Write a program to show the parts of the URL.
The URL class is part of the [Link] package and represents a Uniform Resource Locator
(URL) that can be used to describe the address of a resource on the internet. It provides methods
to extract different components of a URL such as the protocol, host, port, path, query, etc.

URL Components:

A URL generally has the following components:

1. Protocol: The protocol used for communication (e.g., HTTP, HTTPS, FTP).
2. Host: The domain name or IP address of the server.
3. Port: The port number used for the connection (optional; default values are used if not
specified).
4. Path: The specific resource or path on the server (e.g., /[Link]).
5. Query: The query string used for passing parameters (optional; e.g., ?id=123).
6. Fragment: The fragment identifier (optional; used for navigating to a specific part of the
resource, e.g., #section1).

import [Link];

public class URLParts {


public static void main(String[] args) {
try {
// Create a URL object
URL url = new URL("[Link]
name=value#section");

// Display the parts of the URL


[Link]("Full URL: " + [Link]());
[Link]("Protocol: " + [Link]());
[Link]("Host: " + [Link]());
[Link]("Port: " + [Link]());
[Link]("Path: " + [Link]());
[Link]("Query: " + [Link]());
[Link]("Fragment: " + [Link]());
} catch (Exception e) {
[Link]();
}
}
}

9. Define cookies. Write a program to retrieve cookie information stored in the system.
Cookies are small pieces of data that are sent by a server and stored on the client's
system. They are primarily used for maintaining session information, user preferences, or
tracking user activity.

In Java, cookies are typically managed using the HttpCookie class from the [Link] package,
especially in web applications where cookies are exchanged between the client and server.

import [Link].*;

import [Link].*;

import [Link].*;

public class RetrieveCookiesServlet extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {

// Set the response content type

[Link]("text/html");

// Get cookies from the request

Cookie[] cookies = [Link]();

// Check if cookies are present

if (cookies != null) {

PrintWriter out = [Link]();

[Link]("<h2>Cookie Information:</h2>");

for (Cookie cookie : cookies) {

[Link]("<p>Cookie Name: " + [Link]() + "</p>");

[Link]("<p>Cookie Value: " + [Link]() + "</p>");

[Link]("<p>Cookie Domain: " + [Link]() + "</p>");


[Link]("<p>Cookie Path: " + [Link]() + "</p>");

[Link]("<p>Cookie Max Age: " + [Link]() + "</p>");

[Link]("<p>Cookie Secure: " + [Link]() + "</p>");

} else {

[Link]().println("<p>No cookies found.</p>");

Network programming is the process of writing software applications that can communicate
over a network. This involves using network protocols (such as TCP/IP, UDP) to allow
communication between devices across a local area network (LAN) or wide area network
(WAN) like the internet.

In network programming, you typically deal with client-server models, where one device (client)
sends a request and another device (server) responds. The communication could involve sending
or receiving data, such as files, requests for services, or messages between applications.

Features of Network Programming

1. Communication between Devices:


o Network programming allows different devices to communicate over a network,
enabling sharing of data, services, or resources between systems.
o It could involve direct communication between computers (peer-to-peer) or
client-server communication.
2. Use of Sockets:
o Sockets are the primary abstraction for network communication. A socket
represents an endpoint for communication and is used to send and receive data.
o A server socket listens for incoming connections, while a client socket
establishes a connection to the server.
3. Multiple Protocol Support:
o Network programming supports different communication protocols, such as:
 TCP/IP for reliable, connection-based communication.
 UDP for faster, connectionless communication.
 HTTP/HTTPS for web-based applications.
 FTP, SMTP, and other specialized protocols.
4. Multithreading:
o In network programming, multithreading is often used to handle multiple client
requests simultaneously. Each client connection can be handled in a separate
thread, ensuring efficient use of system resources and quick responses.
o Java provides built-in support for multithreading, which is useful for handling
multiple client connections in server applications.
5. Port Numbers:
o Network communication is done via ports, which are logical channels used for
data transmission. Common ports are 80 for HTTP, 443 for HTTPS, and 21 for
FTP.
o Server applications listen to specific ports, while client applications connect to
those ports.
6. Addressing and Naming:
o Network programming also involves the use of IP addresses and domain names
for identifying devices on the network.
o DNS (Domain Name System) is used to resolve domain names into IP addresses.
7. Error Handling and Security:
o Robust error handling is essential in network programming due to potential
issues like timeouts, server unavailability, or incorrect data transmission.
o Security features like SSL/TLS can be used to secure communication and ensure
that the data is transmitted in an encrypted form.
8. Asynchronous Communication:
o In network programming, especially for performance optimization, asynchronous
communication allows a program to initiate a network request and continue
performing other tasks without waiting for the request to complete.
9. Data Serialization:
o Data must be serialized (converted into a byte stream) before it can be transmitted
over the network. Java provides serialization mechanisms that convert objects into
byte streams and vice versa.
10. Connection Management:
o Network programming also involves managing connections (such as opening and
closing sockets), ensuring that the communication is correctly terminated once
data exchange is complete.

Server Code (Socket Server)


The server listens for client connections, receives the message, and sends a response back to the
client.

java
CopyEdit
import [Link].*;
import [Link].*;

public class SocketServer {


public static void main(String[] args) {
try {
// Create a server socket on port 12345
ServerSocket serverSocket = new ServerSocket(12345);
[Link]("Server is waiting for client connection...");

// Wait for client connection


Socket clientSocket = [Link]();
[Link]("Client connected!");

// Create input stream to receive message from client


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

// Create output stream to send response to client


PrintWriter output = new PrintWriter([Link](), true);

// Read the message from the client


String clientMessage = [Link]();
[Link]("Client says: " + clientMessage);

// Send a response back to the client


[Link]("Hello, client! I received your message: " + clientMessage);

// Close the streams and socket


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

} catch (IOException e) {
[Link]();
}
}
}
Client Code (Socket Client)

import [Link].*;

import [Link].*;

public class SocketClient {

public static void main(String[] args) {

try {

// Connect to the server at localhost ([Link]) on port 12345

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

[Link]("Connected to server!");

// Create input stream to read data from the server

BufferedReader input = new BufferedReader(new


InputStreamReader([Link]()));

// Create output stream to send message to the server

PrintWriter output = new PrintWriter([Link](), true);

// Send a message to the server

[Link]("Hello, server! This is the client.");


// Read the response from the server

String serverResponse = [Link]();

[Link]("Server says: " + serverResponse);

// Close the streams and socket

[Link]();

[Link]();

[Link]();

} catch (IOException e) {

[Link]();

}
Program to Print Entire HTTP Header in Java

import [Link].*;

import [Link].*;

public class HttpHeaderPrinter {

public static void main(String[] args) {

try {

// URL to connect to

URL url = new URL("[Link]

// Open connection

HttpURLConnection connection = (HttpURLConnection)


[Link]();

// Send a GET request

[Link]("GET");

// Get the response code (to ensure we get a valid response)

int responseCode = [Link]();

[Link]("Response Code: " + responseCode);


// Get all headers

[Link]("\nHTTP Headers:");

for (String header : [Link]().keySet()) {

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

// Close the connection

[Link]();

} catch (IOException e) {

[Link]();

}
The InetAddress class in Java is part of the [Link] package and provides methods for
dealing with IP addresses, both for resolving hostnames and for network communication. Some
basic features and functionality of the InetAddress class include:

1. Hostname Resolution:
o getByName(String host): Resolves the given hostname (e.g.,
"[Link]") to an InetAddress object, which represents the IP address.
o getHostName(): Returns the hostname associated with the IP address.
2. IP Address Resolution:
o getByName(String host): It can also resolve a host to an IP address, whether
it’s IPv4 or IPv6.
o getHostAddress(): Returns the string representation of the IP address (e.g.,
"[Link]").
3. Localhost Access:
o getLocalHost(): Returns the InetAddress object for the local machine.
4. Checking Reachability:
o isReachable(int timeout): Determines if the host is reachable within a
specified timeout (in milliseconds).
5. Multihoming Support:
o getAllByName(String host): Returns all InetAddress objects associated with
a given host, which can be useful in the case of multiple IP addresses for a
hostname (like in the case of load balancing or multiple network interfaces).
6. Comparison:
o You can compare InetAddress objects using the equals() method to check if
two addresses are the same.
7. IP Type Check:
o isSiteLocalAddress(): Returns true if the address is a site-local address
(private IP).
o isLoopbackAddress(): Checks if the address is a loopback address ([Link] or
equivalent).
Differntaite between url and url classes with example
Point URL Class URLClassLoader Class
Used to load Java classes from external
Represents a URL, a reference to a
1. Purpose locations specified by URLs (e.g., from
resource on the web or local network.
a JAR file or directory).
Helps in parsing, extracting components
2. Dynamically loads Java classes at
(like protocol, host, path), and accessing
Functionality runtime from external locations.
data from a URL.
Used when you need to access or Used when you need to load and use
3. Use Case manipulate resources over the network classes dynamically during the
(e.g., retrieving content from a website).
execution of a program.
getProtocol(), getHost(), loadClass(), getURLs(),
4. Key
getPath(), openStream() to access and getResource() to load classes and
Methods
manage URL components. resources from URLs.
Dynamically loading a class from an
Opening a connection to a webpage and
5. Typical Use external JAR file or directory at
reading its content.
runtime.
Opening and reading content from a Dynamically loading and using a class
6. Example
webpage. from a JAR file.
Works with URLs to find and load class
7. Works with the address or location of a
files, enabling dynamic class loading
Relationship resource, like a website or file.
during program execution.

You might also like