Skip to main content

Ch 16.1 Networking Overview

Networking is the practice of connecting two or more computers or devices via cables or wireless communication to form a network capable of exchanging data. Using Java's java.net package, developers can build network applications without needing deep knowledge of low-level hardware networking.

1. IP Addresses

An IP address is a unique numerical identifier assigned to each device (host) on a network.

  • IPv4: 4-byte address in dotted-decimal form (e.g., 192.168.0.1) — currently being exhausted
  • IPv6: 16-byte next-generation address (e.g., 2001:0db8:85a3::8a2e:0370:7334)

Java uses the InetAddress class to represent and resolve IP addresses.

import java.net.InetAddress;
import java.net.UnknownHostException;

public class InetAddressExample {
public static void main(String[] args) {
try {
// Resolve hostname to IP address
InetAddress ip = InetAddress.getByName("www.google.com");
System.out.println("Host name: " + ip.getHostName());
System.out.println("IP address: " + ip.getHostAddress());

// Get all IP addresses (load-balanced hosts may have multiple)
InetAddress[] allAddresses = InetAddress.getAllByName("www.example.com");
for (InetAddress addr : allAddresses) {
System.out.println("Address: " + addr.getHostAddress());
}

// Local machine's address
InetAddress localhost = InetAddress.getLocalHost();
System.out.println("Localhost: " + localhost.getHostAddress());

// Check if an address is reachable
boolean reachable = ip.isReachable(3000); // 3 second timeout
System.out.println("Reachable: " + reachable);

} catch (UnknownHostException e) {
System.err.println("Host not found: " + e.getMessage());
} catch (java.io.IOException e) {
e.printStackTrace();
}
}
}

2. Port Numbers

If an IP address is a building's street address, a port is the door number within that building.

A single computer (one IP) can run multiple services simultaneously — a web server, a mail server, a database server. Port numbers (0–65535) identify which specific application should receive incoming data.

Well-Known Ports (0–1023)

Reserved by international standards for common system services. Avoid using these for personal applications; use ports 1024 and above instead (e.g., 8080).

PortProtocolService
80HTTPWeb (unencrypted)
443HTTPSWeb (encrypted)
21FTPFile transfer
22SSHSecure shell / remote access
25SMTPEmail sending
3306MySQLMySQL database
5432PostgreSQLPostgreSQL database

3. TCP vs UDP

Network communication protocols differ in reliability and speed.

FeatureTCPUDP
ConnectionConnection-oriented (3-way handshake)Connectionless
ReliabilityGuaranteed delivery and orderingNo guarantee
SpeedSlower (acknowledgment overhead)Faster
Use casesWeb, file transfer, emailVideo streaming, online games, DNS
Java classesServerSocket, SocketDatagramSocket, DatagramPacket
// TCP: establish connection first, then communicate reliably
// Client initiates:
Socket socket = new Socket("192.168.1.1", 8080);
// Server waits:
ServerSocket server = new ServerSocket(8080);
Socket client = server.accept();

// UDP: fire and forget (no connection)
DatagramSocket ds = new DatagramSocket();
byte[] data = "Hello".getBytes();
DatagramPacket packet = new DatagramPacket(data, data.length,
InetAddress.getByName("192.168.1.1"), 8080);
ds.send(packet); // send without waiting for acknowledgment

4. The Client-Server Model

Most network applications follow the client-server model:

  1. Server: Listens on a fixed port, waits for incoming connections
  2. Client: Knows the server's address and port, initiates the connection
Client                          Server
| |
|-- connect(IP:PORT) ---------->|
|<-- accept() returns Socket ---|
| |
|-- send request -------------->|
|<-- receive response ----------|
| |
|-- close() ------------------->|

5. java.net Core Classes

ClassPackagePurpose
InetAddressjava.netRepresents an IP address
URLjava.netRepresents a URL (web address)
URLConnectionjava.netHTTP connection (legacy)
HttpURLConnectionjava.netHTTP GET/POST requests
HttpClientjava.net.httpModern HTTP client (Java 11+)
ServerSocketjava.netTCP server socket
Socketjava.netTCP client/communication socket
DatagramSocketjava.netUDP socket
DatagramPacketjava.netUDP data packet
MulticastSocketjava.netUDP multicast

6. Network I/O is Stream-Based

Network communication in Java uses the same I/O streams you learned in Chapter 15. A Socket object provides InputStream and OutputStream — you read and write data through them exactly as you would with a file.

import java.net.*;
import java.io.*;

public class SocketStreamDemo {
public static void main(String[] args) throws IOException {
try (Socket socket = new Socket("echo.example.com", 7)) { // echo service

// Get the socket's I/O streams
InputStream rawIn = socket.getInputStream();
OutputStream rawOut = socket.getOutputStream();

// Wrap them for convenient text communication
BufferedReader in = new BufferedReader(new InputStreamReader(rawIn));
PrintWriter out = new PrintWriter(rawOut, true); // autoFlush

// Send a message
out.println("Hello, server!");

// Receive the echo
String response = in.readLine();
System.out.println("Server replied: " + response);
}
}
}

7. Practical Example: Simple Network Information Tool

import java.net.*;
import java.util.*;

public class NetworkInfo {
public static void main(String[] args) throws Exception {
System.out.println("=== Network Information ===");

// Local hostname and IP
InetAddress local = InetAddress.getLocalHost();
System.out.println("Hostname: " + local.getHostName());
System.out.println("Local IP: " + local.getHostAddress());
System.out.println("Loopback: " + InetAddress.getByName("localhost").getHostAddress());

// Enumerate all network interfaces
System.out.println("\n=== Network Interfaces ===");
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface ni = interfaces.nextElement();
if (!ni.isUp() || ni.isLoopback()) continue;

System.out.println("Interface: " + ni.getDisplayName());
Enumeration<InetAddress> addrs = ni.getInetAddresses();
while (addrs.hasMoreElements()) {
InetAddress addr = addrs.nextElement();
System.out.println(" Address: " + addr.getHostAddress()
+ (addr instanceof Inet4Address ? " (IPv4)" : " (IPv6)"));
}
}

// Resolve common hostnames
System.out.println("\n=== DNS Lookup ===");
String[] hosts = {"www.google.com", "www.github.com"};
for (String host : hosts) {
try {
InetAddress addr = InetAddress.getByName(host);
System.out.printf("%-20s -> %s%n", host, addr.getHostAddress());
} catch (UnknownHostException e) {
System.out.printf("%-20s -> FAILED (no network?)%n", host);
}
}
}
}
tip

Pro tip: When building production network applications:

  • Always set socket timeouts (socket.setSoTimeout(ms)) to prevent hanging indefinitely
  • Handle SocketTimeoutException, ConnectException, and SocketException explicitly
  • Use try-with-resources for all Socket and ServerSocket objects
  • For high-concurrency servers, consider Java NIO's non-blocking channels (java.nio.channels) or a framework like Netty
  • For HTTP communication, prefer Java 11+'s HttpClient over HttpURLConnection