我可以从JVM内部了解jdwp传输端口吗?

时间:2011-11-21 17:35:16

标签: java remote-debugging jdwp

我使用以下参数启动java:
-Xdebug -Xrunjdwp:transport=dt_socket,address=0,server=y,suspend=n
 我得到以下输出:
Listening for transport dt_socket at address: 59183

是否可以从同一个JVM中找到端口,而无需读取标准输出?

2 个答案:

答案 0 :(得分:1)

为什么要将端口设置为0?通常,您可以使用address参数将端口设置为您想要的任何端口。

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

答案 1 :(得分: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;
    }
}