Java Networking: IP, Sockets, and HTTP Methods
Display IP and MAC Address in Java
This program displays the IP address and MAC address of the system and checks whether the IP address is IPv4 or IPv6.
import java.net.*;
public class SimpleNetworkInfo {
public static void main(String[] args) {
try {
InetAddress ip = InetAddress.getLocalHost();
System.out.println("IP Address: " + ip.getHostAddress());
String ipType = (ip instanceof Inet4Address) ? "IPv4" : "IPv6";
System.out.println("IP Type: " + ipType);
NetworkInterface network = NetworkInterface.getByInetAddress(ip);
byte[] mac = network.getHardwareAddress();
if (mac != null) {
StringBuilder macAddress = new StringBuilder();
for (int i = 0; i < mac.length; i++) {
macAddress.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
}
System.out.println("MAC Address: " + macAddress);
}
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}Defining the URL Class and Splitting URLs
The java.net.URL class represents a Uniform Resource Locator (URL), which points to a resource on the internet.
Example: Splitting a URL into Parts
import java.net.URL;
public class URLSplitter {
public static void main(String[] args) {
try {
URL url = new URL("https://www.example.com:8080/path/page.html?user=john&id=101");
System.out.println("URL: " + url.toString());
System.out.println("Protocol: " + url.getProtocol());
System.out.println("Host: " + url.getHost());
System.out.println("Port: " + url.getPort());
System.out.println("Path: " + url.getPath());
System.out.println("File: " + url.getFile());
System.out.println("Query: " + url.getQuery());
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}Defining Cookies and Retrieving Stored Information
Cookies are small pieces of data stored on the client side. This program demonstrates how to retrieve cookie information stored in the system.
import java.net.*;
import java.util.List;
public class RetrieveCookies {
public static void main(String[] args) {
try {
CookieManager cookieManager = new CookieManager();
CookieHandler.setDefault(cookieManager);
URL url = new URL("https://www.example.com");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.getContent(); // Send request to store cookies
CookieStore cookieStore = cookieManager.getCookieStore();
List<HttpCookie> cookies = cookieStore.getCookies();
if (cookies.isEmpty()) {
System.out.println("No cookies found.");
} else {
System.out.println("Cookies stored in the system:");
for (HttpCookie cookie : cookies) {
System.out.println("Name: " + cookie.getName());
System.out.println("Value: " + cookie.getValue());
System.out.println("Domain: " + cookie.getDomain());
System.out.println("Path: " + cookie.getPath());
System.out.println("----------------------");
}
}
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}Displaying Socket Information
This program displays socket details including the remote address, remote port, local address, and local port.
import java.net.Socket;
public class SocketInfo {
public static void main(String[] args) {
try {
Socket socket = new Socket("google.com", 80);
System.out.println("Remote Address: " + socket.getInetAddress());
System.out.println("Remote Port: " + socket.getPort());
System.out.println("Local Address: " + socket.getLocalAddress());
System.out.println("Local Port: " + socket.getLocalPort());
socket.close();
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}Defining the URLConnection Class
The java.net.URLConnection class represents a communication link between a URL and a Java application. Below is a program to read headers using specific methods.
import java.net.*;
import java.util.Map;
import java.util.List;
public class URLHeaderReader {
public static void main(String[] args) {
try {
URL url = new URL("https://www.example.com");
URLConnection connection = url.openConnection();
connection.connect();
System.out.println("Header Information:");
Map<String, List<String>> headers = connection.getHeaderFields();
for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
String key = entry.getKey();
List<String> values = entry.getValue();
System.out.println((key != null ? key : "Status") + " : " + String.join(", ", values));
}
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}HTTP Methods Explained with Examples
HTTP (HyperText Transfer Protocol) defines several methods to indicate the type of action a client wants to perform on a server resource.
- 1. GET
- Purpose: Retrieve data from the server.
- Characteristics: Safe (does not change data), Idempotent.
- Example:
GET /users HTTP/1.1
- 2. POST
- Purpose: Send data to the server to create a resource.
- Characteristics: Not safe, Not idempotent.
- Example:
POST /users HTTP/1.1
- 3. PUT
- Purpose: Update an existing resource.
- Characteristics: Idempotent.
- Example:
PUT /users/101 HTTP/1.1
- 4. DELETE
- Purpose: Remove a resource from the server.
- Characteristics: Idempotent.
- Example:
DELETE /users/101 HTTP/1.1
- 5. PATCH
- Purpose: Partially update a resource.
- Characteristics: Not necessarily idempotent.
- Example:
PATCH /users/101 HTTP/1.1
- 6. HEAD
- Purpose: Retrieve only headers, no body.
- Characteristics: Safe, Idempotent.
- Example:
HEAD /index.html HTTP/1.1
- 7. OPTIONS
- Purpose: Find out supported methods of a resource.
- Example:
OPTIONS /users HTTP/1.1
Defining Secure Sockets and SSL Clients
A Secure Socket is a network socket that provides encrypted communication between a client and a server using SSL/TLS.
import javax.net.ssl.*;
import java.io.*;
import java.net.*;
public class SecureClient {
public static void main(String[] args) {
try {
SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
SSLSocket socket = (SSLSocket) factory.createSocket("www.google.com", 443);
System.out.println("Connected to server using SSL");
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.println("GET / HTTP/1.1");
out.println("Host: www.google.com");
out.println("Connection: Close");
out.println();
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();
out.close();
socket.close();
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}Java HTTP GET Request Example
This example demonstrates how to perform a standard HTTP GET request to an API endpoint.
import java.net.*;
import java.io.*;
public class HttpGetExample {
public static void main(String[] args) {
try {
URL url = new URL("https://jsonplaceholder.typicode.com/posts/1");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println("Response: " + response.toString());
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}URI vs URL Comparison
| URI (Uniform Resource Identifier) | URL (Uniform Resource Locator) |
|---|---|
| Used to identify a resource | Used to locate a resource |
| Broader concept | Subset of URI |
| May not contain protocol | Always contains protocol |
| Can be URN or URL | Only URL |
| Used mainly for identification | Used mainly for accessing resources |
Applications of URI and URL
| URI Applications | URL Applications |
|---|---|
| Used to uniquely identify resources | Used to access web resources |
| Used in REST APIs to identify endpoints | Used in web browsers to open webpages |
| Used in XML and semantic web technologies | Used to download files from servers |
| Used where identification is required, not access | Used in client–server communication |
| Used to reference namespaces and resources | Used in networking and web applications |
Blocking vs Non-Blocking Socket Communication
| Blocking Socket Communication | Non-Blocking Socket Communication |
|---|---|
| Operations wait until completion | Operations return immediately |
| Thread is blocked during I/O | Thread is not blocked |
Uses java.net.Socket | Uses java.nio package |
| Simpler to implement | More complex to implement |
| One thread per connection | One thread can handle many connections |
| Lower performance for many clients | Better scalability and performance |
