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

Java and The Net

Uploaded by

Aayush Nalawade
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Java and The Net

Uploaded by

Aayush Nalawade
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 19

Java and the Net

The Networking Classes and Interfaces

Presented by:-
Sanskruti Gaikwad
Nidhi Pathak
Aakanksha Khambayat
Aayush Nalawade
Renuka Garad
java.net package:-
Java's networking capabilities are an integral part of its platform,
enabling communication between applications over the network.
The java.net package provides a rich set of classes and interfaces
that simplify network programming tasks such as connecting to
web resources, sending and receiving data over networks, and
implementing both client-side and server-side applications.
Overview of Java Networking Classes and Interfaces The key
classes and interfaces in the java.net package provide different
levels of abstraction for networking tasks.
Here’s a breakdown of the most
important classes and interfaces:
1) InetAddress:
• Purpose:
The InetAddress class represents an IP address (either IPv4 or IPv6) and
is used for both local and remote host address resolution. It provides
methods to get the host name, the IP address as a string, and to check if
the address is reachable.
• Common Methods:
1. InetAddress.getByName(String host): Returns an InetAddress object
for the specified hostname.
2. InetAddress.getLocalHost(): Returns the InetAddress object for the
local machine.
3. InetAddress.isReachable(int timeout): Checks if the host is reachable
within the specified timeout in milliseconds.
Lets understand with a code:-
import java.net.InetAddress;
public class InetAddressExample {
public static void main(String[] args) {
try {
// Get the IP address of a specific website
InetAddress address = InetAddress.getByName("www.google.com");
System.out.println("Hostname: " + address.getHostName());
System.out.println("IP Address: " + address.getHostAddress());
// Get the IP address of the local machine
InetAddress localAddress = InetAddress.getLocalHost();
System.out.println("Local Hostname: " + localAddress.getHostName());
System.out.println("Local IP Address: " + localAddress.getHostAddress());
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output of the code:-
Hostname: www.google.com
IP Address: 142.250.183.68 (this may vary depending on location)
Local Hostname: my-computer-name
Local IP Address: 192.168.1.10 (this may vary based on your
network)
Explanation:-
1. InetAddress.getByName("www.google.com"): Resolves the IP
address of google.com.
2. InetAddress.getLocalHost(): Retrieves the IP address and
hostname of the local machine running the code.
2)URL (Uniform Resource Locator):
• Purpose:
The URL class represents a pointer to a resource on the web (like
a webpage or file). It provides methods to break down and
analyze different parts of the URL, such as the protocol, host,
port, and file path. URLs can be used to create connections to
resources over HTTP, FTP, and other protocols.
• Common Methods:
URL.getProtocol(): Returns the protocol of the URL (e.g., http,
https).
URL.getHost(): Returns the hostname in the
URL.URL.openStream(): Opens an input stream to read data from
the URL resource.
Lets understand with a code:-
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class URLExample {


public static void main(String[] args) {
try {
// Create a URL object for a web resource
URL url = new URL("https://www.example.com/index.html");

// Print various components of the URL


System.out.println("Protocol: " + url.getProtocol());
System.out.println("Host: " + url.getHost());
System.out.println("File: " + url.getFile());
System.out.println("Port: " + url.getPort()); // -1 if the default port is used
// Open a stream to read data from the URL
BufferedReader reader = new BufferedReader(new
InputStreamReader(url.openStream()));

String inputLine;
System.out.println("\nReading data from URL:");
while ((inputLine = reader.readLine()) != null) {
System.out.println(inputLine); // Print each line of the web page
content
}

// Close the stream after reading


reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output of the code
Protocol: https
Host: www.example.com
File: /index.html
Port: -1

Reading data from URL:


<!doctype html>
<html>
<head>
<title>Example Domain</title>
...
</html>
• Explanation:
1. URL url = new
URL("https://www.example.com/index.html"); : This creates a
URL object pointing to the specified web resource.
2. url.getProtocol(), url.getHost(), url.getFile(), url.getPort():
These methods retrieve the protocol (https), host
(www.example.com), file (index.html), and port (if specified;
otherwise returns -1 for the default port).
3. url.openStream(): Opens an input stream to read data from
the specified URL.
4. The BufferedReader reads and prints the content of the web
page line by line.
5. This code fetches and prints the content of
https://www.example.com/index.html, along with key details
of the URL.
3)URLConnection:
• Purpose:
Manages the connection to a web resource (a URL) for both
reading and writing.
• Usage:
Allows you to set up HTTP headers, send data to a server, or
read server responses.
• Key Methods:
1. connect(): Opens a connection to the resource.
2. getInputStream(): Gets an input stream to read data from
the server.
3. setRequestProperty(String key, String value): Sets request
headers.
Lets understand with a code:-
import java.net.URL;
import java.net.URLConnection;
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class URLConnectionExample {


public static void main(String[] args) {
try {
URL url = new URL("https://www.example.com");
URLConnection connection = url.openConnection(); // Open the connection
BufferedReader reader = new BufferedReader(new
InputStreamReader(connection.getInputStream()));
String inputLine;
while ((inputLine = reader.readLine()) != null) {
System.out.println(inputLine);
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output of the code:-
The output of this code will depend on the contents of the URL
you're accessing (in this case, https://www.example.com).
This is the content of the web page at https://www.example.com.
The program reads and prints the HTML structure of the page,
which is typical when reading from a web URL. The output will
vary if you use a different URL.
• Explanation:
1. url.openConnection(): Opens a connection to the specified
URL.
2. connection.getInputStream(): Gets the input stream to read
data from the connection.The code reads the content of the
URL and prints it, line by line.
4)Socket:
• Purpose:
Represents a TCP (Transmission Control Protocol) socket for
communication between two machines.
• Usage:
Allows two-way communication between client and server over
the internet or a network.Key Methods:getInputStream(): Gets
the input stream to receive data.getOutputStream(): Gets the
output stream to send data.close(): Closes the socket
connection.
Lets understand with a code:-
import java.net.Socket;
import java.io.PrintWriter;
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class SocketExample {


public static void main(String[] args) {
try (Socket socket = new Socket("example.com", 80)) {
// Send HTTP GET request
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.println("GET / HTTP/1.1");
out.println("Host: example.com");
out.println("Connection: Close");
out.println(); // Blank line to end the request
// Read response from server
BufferedReader in = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output of the code
HTTP/1.1 200 OK
Content-Encoding: gzip
Accept-Ranges: bytes
Cache-Control: max-age=604800
Content-Type: text/html; charset=UTF-8
Date: Tue, 01 Oct 2024 12:00:00 GMT
Expires: Tue, 08 Oct 2024 12:00:00 GMT
Last-Modified: Tue, 15 Nov 2022 13:00:00 GMT
Server: ECS (nyb/1D38)
Vary: Accept-Encoding
X-Cache: HIT
Content-Length: 648
• Explanation:
1. Socket: Connects to example.com on port 80 (HTTP port).
2. PrintWriter: Sends an HTTP GET request to the server.
3. GET / HTTP/1.1: Requests the root page (/) using HTTP/1.1.
4. Host: example.com: Specifies the host in the request header.
5. Connection: Close: Instructs the server to close the
connection after responding.
6. BufferedReader: Reads the server’s response line by line and
prints it.

You might also like