Java Network Programming
Network Programming Basics
Use Java's InetAddress class to retrieve host information. To get local host details, call the static getLocalHost() method, and use getAllByName() to fetch all IP addresses for a given domain name.
import java.net.InetAddress;
import java.net.UnknownHostException;
public class HostInfoDemo {
public static void main(String[] args) {
try {
InetAddress localHost = InetAddress.getLocalHost();
System.out.println(localHost);
InetAddress[] taobaoHosts = InetAddress.getAllByName("www.taobao.com");
for (InetAddress host : taobaoHosts) {
System.out.printf("Hostname: %s, IP Address: %s%n",
host.getHostName(), host.getHostAddress());
}
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
Test network connectivity by executing system ping commands via Runtime.exec():
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class PingDemo {
public static void main(String[] args) {
try {
Runtime runtime = Runtime.getRuntime();
Process pingProcess = runtime.exec("ping 192.168.1.100");
InputStream inputStream = pingProcess.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
A successful ping repsonse confirms working network connectivity, while timeouts indicate network issues. On Windows systems, use the ipconfig command to view local IP addresses.
TCP Socket Programming
Use Java's ServerSocket class to implement TCP server applications:
- Initialize a
ServerSocketbound to a target port - Call
accept()to listen for incoming client connections, which blocks until a client connects - Retrieve client connection details and read incoming data using standard I/O streams
- Use try-with-resources to automatically close network resources
Example TCP Server code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class TcpServer {
public static void main(String[] args) {
try (ServerSocket tcpServer = new ServerSocket(8081)) {
while (true) {
Socket clientConn = tcpServer.accept();
String clientIp = clientConn.getInetAddress().getHostAddress();
System.out.printf("Client %s connected%n", clientIp);
BufferedReader clientReader = new BufferedReader(
new InputStreamReader(clientConn.getInputStream(), "UTF-8"));
String incomingMsg = clientReader.readLine();
System.out.printf("Client %s says: %s%n", clientIp, incomingMsg);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
TCP Client implementation:
- Create a
Socketinstance to connect to the server's IP address and port - Use output streams to send data to the server, and flush the buffer to ensure immediate transmission
Example TCP Client code:
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class TcpClient {
public static void main(String[] args) {
try (Socket clientSocket = new Socket("192.168.1.100", 8081)) {
BufferedWriter output = new BufferedWriter(
new OutputStreamWriter(clientSocket.getOutputStream()));
output.write("Hello from TCP client!");
output.flush();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
TCP uses stream-based communication, so Socket provides getInputStream() and getOutputStream() for reading and writing network data, identical to standard Java I/O operations.
UDP Socket Programming
UDP server implementation uses DatagramSocket and DatagramPacket:
- Create a
DatagramSocketbound to a listening port - Initialiez a
DatagramPacketto receive incoming network data - Use
receive()to wait for incoming packets - Process received data and send a response packet if needed
Example UDP Server code:
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class UdpServer {
public static void main(String[] args) {
try (DatagramSocket udpServer = new DatagramSocket(5000)) {
byte[] buffer = new byte[1024];
DatagramPacket incomingPacket = new DatagramPacket(buffer, buffer.length);
udpServer.receive(incomingPacket);
String receivedMsg = new String(incomingPacket.getData(), 0, incomingPacket.getLength()).trim();
System.out.printf("Received from client: %s%n", receivedMsg);
String response = "天王盖地虎".equals(receivedMsg) ? "宝塔镇河妖" : "error~";
incomingPacket.setData(response.getBytes());
udpServer.send(incomingPacket);
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
UDP Client implementation:
- Create a
DatagramSocketwithout binding to a specific port - Connect to the target server's address and port
- Create and send a
DatagramPacketwith outgoing data - Wait for a response packet using
receive()
Example UDP Client code:
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
public class UdpClient {
public static void main(String[] args) {
try (DatagramSocket udpClient = new DatagramSocket()) {
udpClient.connect(InetAddress.getByName("192.168.1.100"), 5000);
byte[] sendData = "天王盖地虎".getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length);
udpClient.send(sendPacket);
byte[] recvBuffer = new byte[1024];
DatagramPacket recvPacket = new DatagramPacket(recvBuffer, recvBuffer.length);
udpClient.receive(recvPacket);
String response = new String(recvPacket.getData(), 0, recvPacket.getLength());
System.out.printf("Received from server: %s%n", response);
} catch (SocketException | UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}