2

I am starting java with the following arguments:
-Xdebug -Xrunjdwp:transport=dt_socket,address=0,server=y,suspend=n
and I get the following output:
Listening for transport dt_socket at address: 59183

Is it possible to find the port from inside the same JVM, without reading standard output?

javabrett
  • 7,020
  • 4
  • 51
  • 73
oshai
  • 14,865
  • 26
  • 84
  • 140
  • https://stackoverflow.com/questions/28745065/identify-java-jdwp-debugger-assigned-ephemeral-port – shawn Jun 07 '17 at 04:06

2 Answers2

1
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Method;
import java.util.Properties;

@Slf4j
public class RuntimeDebugger {

    static private int jdwpListenerPort;

    static public int getJdwpListenerPort() {
        if(jdwpListenerPort == 0) {
            jdwpListenerPort = readJdwpListenerPort();
        }
        return jdwpListenerPort;
    }

    static private int readJdwpListenerPort() {
        String listenerAddress = null;
        try {
            Class<?> theClass = Class.forName("sun.misc.VMSupport");
            Method m = theClass.getMethod("getAgentProperties");
            Properties p = (Properties) m.invoke(null);
            listenerAddress = p.getProperty("sun.jdwp.listenerAddress");
            if (listenerAddress != null) {
                listenerAddress = StringUtils.substringAfter(listenerAddress, ":");
                return Integer.parseInt(listenerAddress);
            }
        } catch (Exception ex) {
            log.error("Failed to read sun.jdwp.listenerAddress, ignore");
        }
        return -1;
    }
}
shawn
  • 4,305
  • 1
  • 17
  • 25
1

Why are you setting the port to 0? Typically you would use the address parameter to set the port to whatever you want.

http://download.oracle.com/javase/1.4.2/docs/guide/jpda/conninv.html

Dave L.
  • 9,595
  • 7
  • 43
  • 69
  • 2
    I want it to get a free port so it will not fail. I will connect later to that port. – oshai Nov 21 '11 at 17:42
  • @ohadshai -- Where is it documented that using 0 for port will cause it to use an open port? – Dave L. Nov 21 '11 at 17:49
  • I don't know if it's documented, but you can see the result in the question. this is a normal behavior when binding a port. – oshai Nov 21 '11 at 18:40
  • 1
    I see the convention is documented elsewhere even though it is not documented as part of the runjdwp or agentilb stuff: http://download.oracle.com/javase/7/docs/api/java/net/ServerSocket.html#ServerSocket%28int%29 – Dave L. Nov 21 '11 at 23:45