List of usage examples for java.net ServerSocket getLocalPort
public int getLocalPort()
From source file:org.jibble.pircbot.PircBot.java
/** * Attempts to establish a DCC CHAT session with a client. This method * issues the connection request to the client and then waits for the * client to respond. If the connection is successfully made, then a * DccChat object is returned by this method. If the connection is not * made within the time limit specified by the timeout value, then null * is returned.//from ww w .j a v a2 s. c o m * <p/> * It is <b>strongly recommended</b> that you call this method within a new * Thread, as it may take a long time to return. * <p/> * This method may not be overridden. * * @param nick The nick of the user we are trying to establish a chat with. * @param timeout The number of milliseconds to wait for the recipient to * accept the chat connection (we recommend about 120000). * @return a DccChat object that can be used to send and recieve lines of * text. Returns <b>null</b> if the connection could not be made. * @see DccChat * @since PircBot 0.9.8 */ public final DccChat dccSendChatRequest(String nick, int timeout) { DccChat chat = null; try { ServerSocket ss = null; int[] ports = getDccPorts(); if (ports == null) { // Use any free port. ss = new ServerSocket(0); } else { for (int i = 0; i < ports.length; i++) { try { ss = new ServerSocket(ports[i]); // Found a port number we could use. break; } catch (Exception e) { // Do nothing; go round and try another port. } } if (ss == null) { // No ports could be used. throw new IOException("All ports returned by getDccPorts() are in use."); } } ss.setSoTimeout(timeout); int port = ss.getLocalPort(); InetAddress inetAddress = getDccInetAddress(); if (inetAddress == null) { inetAddress = getInetAddress(); } byte[] ip = inetAddress.getAddress(); long ipNum = ipToLong(ip); sendCTCPCommand(nick, "DCC CHAT chat " + ipNum + " " + port); // The client may now connect to us to chat. Socket socket = ss.accept(); // Close the server socket now that we've finished with it. ss.close(); chat = new DccChat(this, nick, socket); } catch (Exception e) { // Do nothing. } return chat; }
From source file:Tcpbw100.java
public boolean test_sfw(Protocol ctl) throws IOException { Message msg = new Message(); if ((tests & TEST_SFW) == TEST_SFW) { showStatus(messages.getString("sfwTest")); results.append(messages.getString("checkingFirewalls") + " "); statistics.append(messages.getString("checkingFirewalls") + " "); emailText = messages.getString("checkingFirewalls") + " "; pub_status = "checkingFirewalls"; if (ctl.recv_msg(msg) != 0) { errmsg = messages.getString("protocolError") + Integer.parseInt(new String(msg.body), 16) + " instead\n"; return true; }/* w w w. j a v a 2 s . c o m*/ if (msg.type != TEST_PREPARE) { errmsg = messages.getString("sfwWrongMessage") + "\n"; if (msg.type == MSG_ERROR) { errmsg += "ERROR MSG: " + Integer.parseInt(new String(msg.body), 16) + "\n"; } return true; } String message = new String(msg.body); int srvPort, testTime; try { int k = message.indexOf(" "); srvPort = Integer.parseInt(message.substring(0, k)); testTime = Integer.parseInt(message.substring(k + 1)); } catch (Exception e) { errmsg = messages.getString("sfwWrongMessage") + "\n"; return true; } System.out.println("SFW: port=" + srvPort); System.out.println("SFW: testTime=" + testTime); ServerSocket srvSocket; try { SecurityManager security = System.getSecurityManager(); if (security != null) { System.out.println("Asking security manager for listen permissions..."); security.checkListen(0); } srvSocket = new ServerSocket(0); } catch (Exception e) { e.printStackTrace(); errmsg = messages.getString("sfwSocketFail") + "\n"; return true; } System.out.println("SFW: oport=" + srvSocket.getLocalPort()); ctl.send_msg(TEST_MSG, Integer.toString(srvSocket.getLocalPort()).getBytes()); if (ctl.recv_msg(msg) != 0) { errmsg = messages.getString("protocolError") + Integer.parseInt(new String(msg.body), 16) + " instead\n"; return true; } if (msg.type != TEST_START) { errmsg = messages.getString("sfwWrongMessage"); if (msg.type == MSG_ERROR) { errmsg += "ERROR MSG: " + Integer.parseInt(new String(msg.body), 16) + "\n"; } return true; } OsfwWorker osfwTest = new OsfwWorker(srvSocket, testTime); new Thread(osfwTest).start(); Socket sfwSocket = new Socket(); try { sfwSocket.connect(new InetSocketAddress(host, srvPort), testTime * 1000); Protocol sfwCtl = new Protocol(sfwSocket); sfwCtl.send_msg(TEST_MSG, new String("Simple firewall test").getBytes()); } catch (Exception e) { e.printStackTrace(); } if (ctl.recv_msg(msg) != 0) { errmsg = messages.getString("protocolError") + Integer.parseInt(new String(msg.body), 16) + " instead\n"; return true; } if (msg.type != TEST_MSG) { errmsg = messages.getString("sfwWrongMessage") + "\n"; if (msg.type == MSG_ERROR) { errmsg += "ERROR MSG: " + Integer.parseInt(new String(msg.body), 16) + "\n"; } return true; } c2sResult = Integer.parseInt(new String(msg.body)); osfwTest.finalize(); if (ctl.recv_msg(msg) != 0) { errmsg = messages.getString("protocolError") + Integer.parseInt(new String(msg.body), 16) + " instead\n"; return true; } if (msg.type != TEST_FINALIZE) { errmsg = messages.getString("sfwWrongMessage") + "\n"; if (msg.type == MSG_ERROR) { errmsg += "ERROR MSG: " + Integer.parseInt(new String(msg.body), 16) + "\n"; } return true; } results.append(messages.getString("done") + "\n"); statistics.append(messages.getString("done") + "\n"); emailText += messages.getString("done") + "\n%0A"; } return false; }
From source file:com.atomicleopard.thundr.ftp.commons.FTPClient.java
/** * Establishes a data connection with the FTP server, returning * a Socket for the connection if successful. If a restart * offset has been set with {@link #setRestartOffset(long)}, * a REST command is issued to the server with the offset as * an argument before establishing the data connection. Active * mode connections also cause a local PORT command to be issued. * <p>/*from w w w . ja va 2s. c om*/ * @param command The text representation of the FTP command to send. * @param arg The arguments to the FTP command. If this parameter is * set to null, then the command is sent with no argument. * @return A Socket corresponding to the established data connection. * Null is returned if an FTP protocol error is reported at * any point during the establishment and initialization of * the connection. * @exception IOException If an I/O error occurs while either sending a * command to the server or receiving a reply from the server. * @since 3.1 */ protected Socket _openDataConnection_(String command, String arg) throws IOException { if (__dataConnectionMode != ACTIVE_LOCAL_DATA_CONNECTION_MODE && __dataConnectionMode != PASSIVE_LOCAL_DATA_CONNECTION_MODE) { return null; } final boolean isInet6Address = getRemoteAddress() instanceof Inet6Address; Socket socket; if (__dataConnectionMode == ACTIVE_LOCAL_DATA_CONNECTION_MODE) { // if no activePortRange was set (correctly) -> getActivePort() = 0 // -> new ServerSocket(0) -> bind to any free local port ServerSocket server = _serverSocketFactory_.createServerSocket(getActivePort(), 1, getHostAddress()); try { // Try EPRT only if remote server is over IPv6, if not use PORT, // because EPRT has no advantage over PORT on IPv4. // It could even have the disadvantage, // that EPRT will make the data connection fail, because // today's intelligent NAT Firewalls are able to // substitute IP addresses in the PORT command, // but might not be able to recognize the EPRT command. if (isInet6Address) { if (!FTPReply.isPositiveCompletion(eprt(getReportHostAddress(), server.getLocalPort()))) { return null; } } else { if (!FTPReply.isPositiveCompletion(port(getReportHostAddress(), server.getLocalPort()))) { return null; } } if ((__restartOffset > 0) && !restart(__restartOffset)) { return null; } if (!FTPReply.isPositivePreliminary(sendCommand(command, arg))) { return null; } // For now, let's just use the data timeout value for waiting for // the data connection. It may be desirable to let this be a // separately configurable value. In any case, we really want // to allow preventing the accept from blocking indefinitely. if (__dataTimeout >= 0) { server.setSoTimeout(__dataTimeout); } socket = server.accept(); // Ensure the timeout is set before any commands are issued on the new socket if (__dataTimeout >= 0) { socket.setSoTimeout(__dataTimeout); } if (__receiveDataSocketBufferSize > 0) { socket.setReceiveBufferSize(__receiveDataSocketBufferSize); } if (__sendDataSocketBufferSize > 0) { socket.setSendBufferSize(__sendDataSocketBufferSize); } } finally { server.close(); } } else { // We must be in PASSIVE_LOCAL_DATA_CONNECTION_MODE // Try EPSV command first on IPv6 - and IPv4 if enabled. // When using IPv4 with NAT it has the advantage // to work with more rare configurations. // E.g. if FTP server has a static PASV address (external network) // and the client is coming from another internal network. // In that case the data connection after PASV command would fail, // while EPSV would make the client succeed by taking just the port. boolean attemptEPSV = isUseEPSVwithIPv4() || isInet6Address; if (attemptEPSV && epsv() == FTPReply.ENTERING_EPSV_MODE) { _parseExtendedPassiveModeReply(_replyLines.get(0)); } else { if (isInet6Address) { return null; // Must use EPSV for IPV6 } // If EPSV failed on IPV4, revert to PASV if (pasv() != FTPReply.ENTERING_PASSIVE_MODE) { return null; } _parsePassiveModeReply(_replyLines.get(0)); } socket = _socketFactory_.createSocket(); if (__receiveDataSocketBufferSize > 0) { socket.setReceiveBufferSize(__receiveDataSocketBufferSize); } if (__sendDataSocketBufferSize > 0) { socket.setSendBufferSize(__sendDataSocketBufferSize); } if (__passiveLocalHost != null) { socket.bind(new InetSocketAddress(__passiveLocalHost, 0)); } // For now, let's just use the data timeout value for waiting for // the data connection. It may be desirable to let this be a // separately configurable value. In any case, we really want // to allow preventing the accept from blocking indefinitely. if (__dataTimeout >= 0) { socket.setSoTimeout(__dataTimeout); } socket.connect(new InetSocketAddress(__passiveHost, __passivePort), connectTimeout); if ((__restartOffset > 0) && !restart(__restartOffset)) { socket.close(); return null; } if (!FTPReply.isPositivePreliminary(sendCommand(command, arg))) { socket.close(); return null; } } if (__remoteVerificationEnabled && !verifyRemote(socket)) { socket.close(); throw new IOException("Host attempting data connection " + socket.getInetAddress().getHostAddress() + " is not same as server " + getRemoteAddress().getHostAddress()); } return socket; }
From source file:org.pentaho.di.trans.step.BaseStep.java
@Override public void cleanup() { for (ServerSocket serverSocket : serverSockets) { try {/*w w w.ja v a2s . c om*/ socketRepository.releaseSocket(serverSocket.getLocalPort()); logDetailed(BaseMessages.getString(PKG, "BaseStep.Log.ReleasedServerSocketOnPort", serverSocket.getLocalPort())); } catch (IOException e) { logError("Cleanup: Unable to release server socket (" + serverSocket.getLocalPort() + ")", e); } } List<RemoteStep> remoteInputSteps = getRemoteInputSteps(); if (remoteInputSteps != null) { cleanupRemoteSteps(remoteInputSteps); } List<RemoteStep> remoteOutputSteps = getRemoteOutputSteps(); if (remoteOutputSteps != null) { cleanupRemoteSteps(remoteOutputSteps); } }
From source file:org.pentaho.di.trans.step.BaseStep.java
@Override public boolean init(StepMetaInterface smi, StepDataInterface sdi) { sdi.setStatus(StepExecutionStatus.STATUS_INIT); String slaveNr = transMeta.getVariable(Const.INTERNAL_VARIABLE_SLAVE_SERVER_NUMBER); String clusterSize = transMeta.getVariable(Const.INTERNAL_VARIABLE_CLUSTER_SIZE); boolean master = "Y".equalsIgnoreCase(transMeta.getVariable(Const.INTERNAL_VARIABLE_CLUSTER_MASTER)); if (!Utils.isEmpty(slaveNr) && !Utils.isEmpty(clusterSize) && !master) { this.slaveNr = Integer.parseInt(slaveNr); this.clusterSize = Integer.parseInt(clusterSize); if (log.isDetailed()) { logDetailed(BaseMessages.getString(PKG, "BaseStep.Log.ReleasedServerSocketOnPort", slaveNr, clusterSize));//from w w w . j a v a2 s .c o m } } else { this.slaveNr = 0; this.clusterSize = 0; } // Also set the internal variable for the partition // SlaveStepCopyPartitionDistribution partitionDistribution = transMeta .getSlaveStepCopyPartitionDistribution(); if (stepMeta.isPartitioned()) { // See if we are partitioning remotely // if (partitionDistribution != null && !partitionDistribution.getDistribution().isEmpty()) { String slaveServerName = getVariable(Const.INTERNAL_VARIABLE_SLAVE_SERVER_NAME); int stepCopyNr = stepcopy; // Look up the partition nr... // Set the partition ID (string) as well as the partition nr [0..size[ // PartitionSchema partitionSchema = stepMeta.getStepPartitioningMeta().getPartitionSchema(); int partitionNr = partitionDistribution.getPartition(slaveServerName, partitionSchema.getName(), stepCopyNr); if (partitionNr >= 0) { String partitionNrString = new DecimalFormat("000").format(partitionNr); setVariable(Const.INTERNAL_VARIABLE_STEP_PARTITION_NR, partitionNrString); if (partitionDistribution.getOriginalPartitionSchemas() != null) { // What is the partition schema name? // String partitionSchemaName = stepMeta.getStepPartitioningMeta().getPartitionSchema() .getName(); // Search the original partition schema in the distribution... // for (PartitionSchema originalPartitionSchema : partitionDistribution .getOriginalPartitionSchemas()) { String slavePartitionSchemaName = TransSplitter .createSlavePartitionSchemaName(originalPartitionSchema.getName()); if (slavePartitionSchemaName.equals(partitionSchemaName)) { PartitionSchema schema = (PartitionSchema) originalPartitionSchema.clone(); // This is the one... // if (schema.isDynamicallyDefined()) { schema.expandPartitionsDynamically(this.clusterSize, this); } String partID = schema.getPartitionIDs().get(partitionNr); setVariable(Const.INTERNAL_VARIABLE_STEP_PARTITION_ID, partID); break; } } } } } else { // This is a locally partitioned step... // int partitionNr = stepcopy; String partitionNrString = new DecimalFormat("000").format(partitionNr); setVariable(Const.INTERNAL_VARIABLE_STEP_PARTITION_NR, partitionNrString); final List<String> partitionIDList = stepMeta.getStepPartitioningMeta().getPartitionSchema() .getPartitionIDs(); if (partitionIDList.size() > 0) { String partitionID = partitionIDList.get(partitionNr); setVariable(Const.INTERNAL_VARIABLE_STEP_PARTITION_ID, partitionID); } else { logError(BaseMessages.getString(PKG, "BaseStep.Log.UnableToRetrievePartitionId", stepMeta.getStepPartitioningMeta().getPartitionSchema().getName())); return false; } } } else if (!Utils.isEmpty(partitionID)) { setVariable(Const.INTERNAL_VARIABLE_STEP_PARTITION_ID, partitionID); } // Set a unique step number across all slave servers // // slaveNr * nrCopies + copyNr // uniqueStepNrAcrossSlaves = this.slaveNr * getStepMeta().getCopies() + stepcopy; uniqueStepCountAcrossSlaves = this.clusterSize <= 1 ? getStepMeta().getCopies() : this.clusterSize * getStepMeta().getCopies(); if (uniqueStepCountAcrossSlaves == 0) { uniqueStepCountAcrossSlaves = 1; } setVariable(Const.INTERNAL_VARIABLE_STEP_UNIQUE_NUMBER, Integer.toString(uniqueStepNrAcrossSlaves)); setVariable(Const.INTERNAL_VARIABLE_STEP_UNIQUE_COUNT, Integer.toString(uniqueStepCountAcrossSlaves)); setVariable(Const.INTERNAL_VARIABLE_STEP_COPYNR, Integer.toString(stepcopy)); // BACKLOG-18004 allowEmptyFieldNamesAndTypes = Boolean.parseBoolean( System.getProperties().getProperty(Const.KETTLE_ALLOW_EMPTY_FIELD_NAMES_AND_TYPES, "false")); // Now that these things have been done, we also need to start a number of server sockets. // One for each of the remote output steps that we're going to write to. // try { // If this is on the master, separate logic applies. // // boolean isMaster = "Y".equalsIgnoreCase(getVariable(Const.INTERNAL_VARIABLE_CLUSTER_MASTER)); remoteOutputSteps = new ArrayList<RemoteStep>(); for (int i = 0; i < stepMeta.getRemoteOutputSteps().size(); i++) { RemoteStep remoteStep = stepMeta.getRemoteOutputSteps().get(i); // If the step run in multiple copies, we only want to open every socket once. // if (getCopy() == remoteStep.getSourceStepCopyNr()) { // Open a server socket to allow the remote output step to connect. // RemoteStep copy = (RemoteStep) remoteStep.clone(); try { if (log.isDetailed()) { logDetailed(BaseMessages.getString(PKG, "BaseStep.Log.SelectedRemoteOutputStepToServer", copy, copy.getTargetStep(), copy.getTargetStepCopyNr(), copy.getPort())); } copy.openServerSocket(this); if (log.isDetailed()) { logDetailed(BaseMessages.getString(PKG, "BaseStep.Log.OpenedServerSocketConnectionTo", copy)); } } catch (Exception e) { logError("Unable to open server socket during step initialisation: " + copy.toString(), e); throw e; } remoteOutputSteps.add(copy); } } } catch (Exception e) { for (RemoteStep remoteStep : remoteOutputSteps) { if (remoteStep.getServerSocket() != null) { try { ServerSocket serverSocket = remoteStep.getServerSocket(); getTrans().getSocketRepository().releaseSocket(serverSocket.getLocalPort()); } catch (IOException e1) { logError("Unable to close server socket after error during step initialisation", e); } } } return false; } // For the remote input steps to read from, we do the same: make a list and initialize what we can... // try { remoteInputSteps = new ArrayList<RemoteStep>(); if ((stepMeta.isPartitioned() && getClusterSize() > 1) || stepMeta.getCopies() > 1) { // If the step is partitioned or has multiple copies and clustered, we only want to take one remote input step // per copy. // This is where we make that selection... // for (int i = 0; i < stepMeta.getRemoteInputSteps().size(); i++) { RemoteStep remoteStep = stepMeta.getRemoteInputSteps().get(i); if (remoteStep.getTargetStepCopyNr() == stepcopy) { RemoteStep copy = (RemoteStep) remoteStep.clone(); remoteInputSteps.add(copy); } } } else { for (RemoteStep remoteStep : stepMeta.getRemoteInputSteps()) { RemoteStep copy = (RemoteStep) remoteStep.clone(); remoteInputSteps.add(copy); } } } catch (Exception e) { logError("Unable to initialize remote input steps during step initialisation", e); return false; } // Getting ans setting the error handling values // first, get the step meta StepErrorMeta stepErrorMeta = stepMeta.getStepErrorMeta(); if (stepErrorMeta != null) { // do an environment substitute for stepErrorMeta.getMaxErrors(), stepErrorMeta.getMinPercentRows() // and stepErrorMeta.getMaxPercentErrors() // Catch NumberFormatException since the user can enter anything in the dialog- the value // they enter must be a number or a variable set to a number // We will use a boolean to indicate failure so that we can log all errors - not just the first one caught boolean envSubFailed = false; try { maxErrors = (!Utils.isEmpty(stepErrorMeta.getMaxErrors()) ? Long.valueOf(trans.environmentSubstitute(stepErrorMeta.getMaxErrors())) : -1L); } catch (NumberFormatException nfe) { log.logError(BaseMessages.getString(PKG, "BaseStep.Log.NumberFormatException", BaseMessages.getString(PKG, "BaseStep.Property.MaxErrors.Name"), this.stepname, (stepErrorMeta.getMaxErrors() != null ? stepErrorMeta.getMaxErrors() : ""))); envSubFailed = true; } try { minRowsForMaxErrorPercent = (!Utils.isEmpty(stepErrorMeta.getMinPercentRows()) ? Long.valueOf(trans.environmentSubstitute(stepErrorMeta.getMinPercentRows())) : -1L); } catch (NumberFormatException nfe) { log.logError(BaseMessages.getString(PKG, "BaseStep.Log.NumberFormatException", BaseMessages.getString(PKG, "BaseStep.Property.MinRowsForErrorsPercentCalc.Name"), this.stepname, (stepErrorMeta.getMinPercentRows() != null ? stepErrorMeta.getMinPercentRows() : ""))); envSubFailed = true; } try { maxPercentErrors = (!Utils.isEmpty(stepErrorMeta.getMaxPercentErrors()) ? Integer.valueOf(trans.environmentSubstitute(stepErrorMeta.getMaxPercentErrors())) : -1); } catch (NumberFormatException nfe) { log.logError(BaseMessages.getString(PKG, "BaseStep.Log.NumberFormatException", BaseMessages.getString(PKG, "BaseStep.Property.MaxPercentErrors.Name"), this.stepname, (stepErrorMeta.getMaxPercentErrors() != null ? stepErrorMeta.getMaxPercentErrors() : ""))); envSubFailed = true; } // if we failed and environment subsutitue if (envSubFailed) { return false; } } return true; }