2017-02-23 163 views
1

我正在測試MSSQL。 「如何在連接後長時間創建會話信息?」如何從jdbc連接知道客戶端ip端口

因此,嘗試連接MSSQL JDBC,然後選擇與客戶端IP和端口的sys.dm_exec_session和sys.dm_exec_connection。

但是,我沒有任何想法,如何從JDBC連接獲取客戶端IP和端口。

或者是否有可能使用套接字創建JDBC連接?

顯示我的測試代碼。

try { 
     DriverManager.registerDriver(
       new com.microsoft.sqlserver.jdbc.SQLServerDriver()); 
     DriverManager.setLoginTimeout(10); 
    } catch (Exception ex) { 
     System.out.println("Fail to register sqlserver driver."); 
     return; 
    } 

    String url = "jdbc:sqlserver://"; 
    String ip = "10.1.1.1"; 
    String port = "1433"; 
    String catalog = "master"; 
    String user = "jtlee"; 
    String pwd = "123456789"; 

    url = url + ip + ":" + port + ";databasename=" + catalog; 

    Connection conn = null; 
    PreparedStatement pstmt = null; 
    ResultSet rs = null; 

    try { 
     long startTime = System.nanoTime(); 

     conn = DriverManager.getConnection(url, user, pwd); 
     pstmt = conn.prepareStatement(
       "SELECT " 
       + "  count(*) " 
       + "FROM " 
       + "  sys.dm_exec_connections connections," 
       + "  sys.dm_exec_sessions sessions " 
       + "WHERE " 
       + "  connections.session_id = sessions.session_id " 
       + "  and connections.client_net_address= ? " 
       + "  and connections.client_tcp_port= ? "); 

     /* I need this information... */ 
     String clientIp; 
     int clientPort; 

     pstmt.setString(1, clientIp); 
     pstmt.setInt(2, clientPort); 
     rs = pstmt.executeQuery(); 

     if (rs.next()) { 
      ... 

感謝您閱讀我奇怪的英語。

回答

2

如果你想獲得一個活動連接的IP和端口你可以查詢sys.dm_exec_connectionsWHERE [email protected]@SPID,例如,

sql = 
     "SELECT client_net_address, client_tcp_port, local_net_address, local_tcp_port " + 
     "FROM sys.dm_exec_connections " + 
     "WHERE [email protected]@SPID"; 
try (
     Statement st = conn.createStatement(); 
     ResultSet rs = st.executeQuery(sql)) { 
    while (rs.next()) { 
     System.out.printf("Connection is between %s:%d on the server and %s:%d as the client.%n", 
       rs.getString("local_net_address"), 
       rs.getInt("local_tcp_port"), 
       rs.getString("client_net_address"), 
       rs.getInt("client_tcp_port") 
       ); 
    } 
} 

生產

Connection is between 192.168.1.12:1433 on the server and 192.168.1.101:49744 as the client. 
相關問題