public MSSqlServerInfo(String host) throws SQLException { try { InetAddress addr = InetAddress.getByName(host); DatagramSocket socket = new DatagramSocket(); byte[] msg = new byte[] {0x02}; DatagramPacket p = new DatagramPacket(msg, msg.length, addr, 1434); socket.send(p); byte[] buf = new byte[4096]; p = new DatagramPacket(buf, buf.length); socket.setSoTimeout(m_timeout); for (int i = 0; i < m_numRetries; i++) { try { socket.receive(p); String infoString = extractString(buf, p.getLength()); m_serverInfoStrings = split(infoString, ';'); return; } catch (InterruptedIOException toEx) { } } } catch (Exception e) { // Ignore... } throw new SQLException(Messages.get("error.msinfo.badinfo", host), "HY000"); }
/** * Call getInfo() before calling this method. It parses the info string returned from SQL Server * and looks for the port for the given named instance. If it can't be found, or if getInfo() * hadsn't been called, it returns -1. * * @param instanceName * @return port the given instance is listening on, or -1 if it can't be found. */ public int getPortForInstance(String instanceName) throws SQLException { if (m_serverInfoStrings == null) { return -1; } // NOTE: default instance is called MSSQLSERVER if (instanceName == null || instanceName.length() == 0) { instanceName = "MSSQLSERVER"; } String curInstance = null; String curPort = null; for (int index = 0; index < m_serverInfoStrings.length; index++) { if (m_serverInfoStrings[index].length() == 0) { curInstance = null; curPort = null; } else { String key = m_serverInfoStrings[index]; String value = ""; index++; if (index < m_serverInfoStrings.length) { value = m_serverInfoStrings[index]; } if (key.equals("InstanceName")) { curInstance = value; } if (key.equals("tcp")) { curPort = value; } if (curInstance != null && curPort != null && curInstance.equalsIgnoreCase(instanceName)) { try { return Integer.parseInt(curPort); } catch (NumberFormatException e) { throw new SQLException(Messages.get("error.msinfo.badport", instanceName), "HY000"); } } } } // didn't find it... return -1; }