import java.io.IOException; import java.io.OutputStream; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; public class SocketTest { public static void main(String[] args) throws IOException { ServerSocket server = new ServerSocket(9999); while(true) { Socket client = server.accept(); MyThread t = new MyThread(client); t.run(); } } } class MyThread extends Thread { private Socket client; public MyThread(Socket client) { this.client = client; } @Override public void run() { try { OutputStream out = client.getOutputStream(); InetAddress address = client.getLocalAddress(); String clientIP = address.getHostAddress(); System.out.println("IP: " + clientIP); String content = "你的IP地址是:" + clientIP; out.write(content.getBytes()); } catch (IOException e) { e.printStackTrace(); } finally { try { client.close(); } catch (IOException e) { e.printStackTrace(); } } } }