Java Networking – Detailed Notes with Examples
1. Introduction to Java Networking
Networking in Java means communication between two or more computers over a network.
Java provides the [Link] package, which includes classes for implementing network operations like
connecting to servers, sending/receiving data, and handling URLs.
Key Classes in [Link]:
InetAddress
Socket and ServerSocket
DatagramPacket and DatagramSocket
URL and URLConnection
2. Internet Addressing
Every device on the internet or local network has a unique IP address (Internet Protocol Address).
Example:
IPv4: [Link]
IPv6: 2001:db8:85a3::8a2e:370:7334
Java represents an IP address using the InetAddress class in [Link].
3. The InetAddress Class
The InetAddress class represents an IP address and provides methods to get host information.
Common Factory Methods:
Method Description
getLocalHost() Returns the local host address
getByName(String host) Gets the IP of a given host name (like [Link])
getAllByName(String host) Returns all IPs of the given host
getHostName() Returns the host name
getHostAddress() Returns the IP address in string form
Example 1: Using InetAddress
import [Link].*;
public class InetAddressExample {
public static void main(String[] args) throws Exception {
InetAddress address = [Link]("[Link]");
[Link]("Host Name: " + [Link]());
[Link]("IP Address: " + [Link]());
InetAddress local = [Link]();
[Link]("Local Host: " + local);
Output (Example):
Host Name: [Link]
IP Address: [Link]
Local Host: LAPTOP-12345/[Link]
4. Instance Methods of InetAddress
Method Description
boolean isReachable(int timeout) Checks if host is reachable
boolean equals(Object obj) Compares two IP addresses
String toString() Returns string representation
boolean isMulticastAddress() Checks if it’s a multicast IP
Example 2: Checking if Host is Reachable
import [Link].*;
public class ReachableExample {
public static void main(String[] args) throws Exception {
InetAddress google = [Link]("[Link]");
if ([Link](3000)) {
[Link]("Google is reachable");
} else {
[Link]("Google is not reachable");
5. TCP/IP Client Sockets
A Socket represents the end-point of a two-way communication link between a client and a server over a
network.
TCP (Transmission Control Protocol) ensures reliable, ordered, and error-checked delivery.
A Client Socket connects to a Server Socket using an IP address and port.
Main Classes:
Socket (for client)
ServerSocket (for server)
Example 3: Simple TCP Client
import [Link].*;
import [Link].*;
public class TCPClient {
public static void main(String[] args) {
try {
Socket s = new Socket("localhost", 6666);
DataOutputStream dout = new DataOutputStream([Link]());
[Link]("Hello Server");
[Link]();
[Link]();
[Link]();
} catch (Exception e) {
[Link](e);
6. TCP/IP Server Sockets
The ServerSocket class listens for incoming connections from clients.
Example 4: Simple TCP Server
import [Link].*;
import [Link].*;
public class TCPServer {
public static void main(String[] args) {
try {
ServerSocket ss = new ServerSocket(6666);
Socket s = [Link](); // waits for a client
DataInputStream dis = new DataInputStream([Link]());
String message = [Link]();
[Link]("Client says: " + message);
[Link]();
} catch (Exception e) {
[Link](e);
Execution:
1. Run TCPServer first (waits for connection).
2. Then run TCPClient.
3. You’ll see:
4. Client says: Hello Server
7. URL and URLConnection
The URL class represents a Uniform Resource Locator, which is a pointer to a resource on the internet.
Java can read data from a URL just like reading from a file.
Example 5: Reading from a Web Page
import [Link].*;
import [Link].*;
public class URLExample {
public static void main(String[] args) throws Exception {
URL url = new URL("[Link]
BufferedReader br = new BufferedReader(new InputStreamReader([Link]()));
String line;
while ((line = [Link]()) != null) {
[Link](line);
[Link]();
}
Example 6: Using URLConnection
import [Link].*;
import [Link].*;
public class URLConnectionExample {
public static void main(String[] args) throws Exception {
URL url = new URL("[Link]
URLConnection conn = [Link]();
[Link]("Content Type: " + [Link]());
[Link]("Date: " + [Link]());
[Link]("Last Modified: " + [Link]());
8. Datagram (UDP Communication)
UDP (User Datagram Protocol) is connectionless, meaning data packets (Datagrams) are sent without
establishing a connection.
Main Classes:
DatagramSocket
DatagramPacket
Example 7: UDP Server
import [Link].*;
public class UDPServer {
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket(3000);
byte[] receive = new byte[1024];
DatagramPacket dp = new DatagramPacket(receive, [Link]);
[Link](dp);
String msg = new String([Link](), 0, [Link]());
[Link]("Client: " + msg);
[Link]();
}
Example 8: UDP Client
import [Link].*;
public class UDPClient {
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket();
String str = "Hello UDP Server";
InetAddress ip = [Link]("localhost");
DatagramPacket dp = new DatagramPacket([Link](), [Link](), ip, 3000);
[Link](dp);
[Link](); }}
Execution:
1. Run the UDPServer first.
2. Then run the UDPClient.
3. You’ll see:
4. Client: Hello UDP Server
Summary Table
Concept Class/Interface Protocol Connection Type Example
IP Addressing InetAddress IP - Getting IP of host
TCP Client Socket TCP Connection-oriented Chat app client
TCP Server ServerSocket TCP Connection-oriented Chat app server
URL URL, URLConnection HTTP/HTTPS Request-based Reading web page
UDP DatagramSocket, DatagramPacket UDP Connectionless Gaming or streaming
Real-World Use Cases
Scenario Technology Used
Chat application TCP (Socket & ServerSocket)
Real-time sensor data UDP (Datagram)
REST API or web scraping URL & URLConnection
Hostname lookup InetAddress