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 e) {
}
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 e) {
}
}
}
catch (IOException e) {
System.err.println(e);
}
}
}
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.
%