// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.net.ServerSocket;
import java.net.SocketImpl;
import java.net.SocketImplFactory;
import java.util.Arrays;
import java.util.stream.Collectors;

public class SocketTrace {
    public static void enableTrace() throws IOException {
        ServerSocket.setSocketFactory(new SocketImplFactory() {
            @Override
            public SocketImpl createSocketImpl() {
                Exception e = new Exception();
                StackTraceElement[] ste = e.getStackTrace();
                String trace = Arrays.stream(ste).skip(4).map(v -> v.getClassName() + "." + v.getMethodName()).collect(Collectors.joining(" "));
                System.out.printf("socket opened from %s\n", trace);
                try {
                    Class<?> stdimpl = Class.forName("java.net.SocksSocketImpl");
                    Constructor<?> ctor = stdimpl.getDeclaredConstructor();
                    ctor.setAccessible(true);
                    return (SocketImpl) ctor.newInstance();
                } catch(Exception ex) {
                    throw new RuntimeException(ex);
                }
            }
        });
    }
    public static void m3() throws IOException {
        ServerSocket s = new ServerSocket(12345);
        s.close();
    }
    public static void m2() throws IOException {
        m3();
    }
    public static void m1() throws IOException {
        m2();
    }
    public static void main(String[] args) throws IOException {
        enableTrace();
        m3();
        m2();
        m1();
    }
}
