Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Java Network Programming

Tech 1

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:

  1. Initialize a ServerSocket bound to a target port
  2. Call accept() to listen for incoming client connections, which blocks until a client connects
  3. Retrieve client connection details and read incoming data using standard I/O streams
  4. 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:

  1. Create a Socket instance to connect to the server's IP address and port
  2. 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:

  1. Create a DatagramSocket bound to a listening port
  2. Initialiez a DatagramPacket to receive incoming network data
  3. Use receive() to wait for incoming packets
  4. 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:

  1. Create a DatagramSocket without binding to a specific port
  2. Connect to the target server's address and port
  3. Create and send a DatagramPacket with outgoing data
  4. 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();
        }
    }
}

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.