The following simple program repeatedly answers client requests by sending back the client's address and port. Then it closes the connection.
import java.net.*;
import java.io.*;
public class HelloServer {
public final static int defaultPort = 2345;
public static void main(String[] args) {
int port = defaultPort;
try {
port = Integer.parseInt(args[0]);
}
catch (Exception ex) {
}
if (port <= 0 || port >= 65536) port = defaultPort;
try {
ServerSocket ss = new ServerSocket(port);
while (true) {
try {
Socket s = ss.accept();
PrintWriter pw = new PrintWriter(s.getOutputStream());
pw.println("Hello " + s.getInetAddress() + " on port "
+ s.getPort());
pw.println("This is " + s.getLocalAddress() + " on port "
+ s.getLocalPort());
pw.flush();
s.close();
}
catch (IOException ex) {
}
}
}
catch (IOException ex) {
System.err.println(ex);
}
}
}
Here's some sample output. note how the port from which the connection comes changes each time.
% telnet utopia.poly.edu 2345 Trying 128.238.3.21... Connected to utopia.poly.edu. Escape character is '^]'. Hello fddisunsite.oit.unc.edu/152.2.254.81 on port 51597 This is utopia.poly.edu/128.238.3.21 on port 2345 Connection closed by foreign host. % !! telnet utopia.poly.edu 2345 Trying 128.238.3.21... Connected to utopia.poly.edu. Escape character is '^]'. Hello fddisunsite.oit.unc.edu/152.2.254.81 on port 51618 This is utopia.poly.edu/128.238.3.21 on port 2345 Connection closed by foreign host. %