While there appears to some documentation on how to expose JMX through various firewall and tunneling schemes, I sort of want the opposite. I want to ensure that JMX is only ac
A bit late answer but if it is still a problem for you (or someone else), I think this will do the trick:
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.net.*;
import java.rmi.registry.LocateRegistry;
import java.rmi.server.RMISocketFactory;
import javax.management.MBeanServer;
import javax.management.remote.*;
public class LocalJMXPort {
public static void main(String[] args) {
try {
int port = 12468;
// Create an instance of our own socket factory (see below)
RMISocketFactory factory = new LocalHostSocketFactory();
// Set it as default
RMISocketFactory.setSocketFactory(factory);
// Create our registry
LocateRegistry.createRegistry(port);
// Get the MBeanServer and setup a JMXConnectorServer
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://127.0.0.1:"+port+"/jndi/rmi://127.0.0.1:"+port+"/jmxrmi");
JMXConnectorServer rmiServer = JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbs);
rmiServer.start();
// Say something
System.out.println("Connect your jconsole to localhost:"+port+". Press a key to exit");
// Wait for a key press
int in = System.in.read();
//Exit
System.out.println("Exiting");
System.exit(0);
} catch(Exception ex) {
ex.printStackTrace();
}
}
static private class LocalHostSocketFactory extends RMISocketFactory {
public ServerSocket createServerSocket(int port) throws IOException {
ServerSocket ret = new ServerSocket();
ret.bind(new InetSocketAddress("localhost", port));
return ret;
}
public Socket createSocket(String host, int port) throws IOException {
return new Socket(host, port);
}
}
}
I just put it together and it is possible that I did something really stupid because my only objective was to have it binding to localhost:port instead of *:port and that part seems to work.
Feel free to comment if there are things that could be bettered or is just plain stupid.