List of usage examples for java.net Socket getLocalAddress
public InetAddress getLocalAddress()
From source file:org.echocat.jomon.net.dns.DnsServer.java
public void TCPclient(Socket s) { try {// w ww . j a v a 2s . co m final int inLength; final DataInputStream dataIn; final DataOutputStream dataOut; final byte[] in; final InputStream is = s.getInputStream(); dataIn = new DataInputStream(is); inLength = dataIn.readUnsignedShort(); in = new byte[inLength]; dataIn.readFully(in); final Message query; byte[] response; try { query = new Message(in); response = generateReply(query, in, in.length, s); if (response == null) { return; } } catch (final IOException ignored) { response = formerrMessage(in); } dataOut = new DataOutputStream(s.getOutputStream()); dataOut.writeShort(response.length); dataOut.write(response); } catch (final IOException e) { LOG.warn("TCPclient(" + addrport(s.getLocalAddress(), s.getLocalPort()) + ").", e); } finally { try { s.close(); } catch (final IOException ignored) { } } }
From source file:net.lightbody.bmp.proxy.jetty.http.HttpContext.java
/** Handler request. * Determine the path within the context and then call * handle(pathInContext,request,response). * @param request/* w ww .j a va 2s . c o m*/ * @param response * @return True if the request has been handled. * @exception HttpException * @exception IOException */ public void handle(HttpRequest request, HttpResponse response) throws HttpException, IOException { if (!isStarted() || _gracefulStop) return; // reject requests by real host if (_hosts != null && _hosts.size() > 0) { Object o = request.getHttpConnection().getConnection(); if (o instanceof Socket) { Socket s = (Socket) o; if (!_hosts.contains(s.getLocalAddress())) { if (log.isDebugEnabled()) log.debug(s.getLocalAddress() + " not in " + _hosts); return; } } } // handle stats if (_statsOn) { synchronized (_statsLock) { _requests++; _requestsActive++; if (_requestsActive > _requestsActiveMax) _requestsActiveMax = _requestsActive; } } String pathInContext = URI.canonicalPath(request.getPath()); if (pathInContext == null) { // Must be a bad request. throw new HttpException(HttpResponse.__400_Bad_Request); } if (_contextPath.length() > 1) pathInContext = pathInContext.substring(_contextPath.length()); if (_redirectNullPath && (pathInContext == null || pathInContext.length() == 0)) { StringBuffer buf = request.getRequestURL(); buf.append("/"); String q = request.getQuery(); if (q != null && q.length() != 0) buf.append("?" + q); response.sendRedirect(buf.toString()); if (log.isDebugEnabled()) log.debug(this + " consumed all of path " + request.getPath() + ", redirect to " + buf.toString()); return; } String pathParams = null; int semi = pathInContext.lastIndexOf(';'); if (semi >= 0) { int pl = pathInContext.length() - semi; String ep = request.getEncodedPath(); if (';' == ep.charAt(ep.length() - pl)) { pathParams = pathInContext.substring(semi + 1); pathInContext = pathInContext.substring(0, semi); } } try { handle(pathInContext, pathParams, request, response); } finally { if (_userRealm != null && request.hasUserPrincipal()) _userRealm.disassociate(request.getUserPrincipal()); } }
From source file:org.jibble.pircbot.PircBot.java
/** * Attempt to connect to the specified IRC server using the supplied * password./*from w ww .j a va 2s . c o m*/ * The onConnect method is called upon success. * * @param hostname The hostname of the server to connect to. * @param port The port number to connect to on the server. * @param password The password to use to join the server. * @throws IOException if it was not possible to connect to the server. * @throws IrcException if the server would not let us join it. * @throws NickAlreadyInUseException if our nick is already in use on the server. */ public final synchronized void connect(String hostname, int port, String password) throws IOException, IrcException, NickAlreadyInUseException { _server = hostname; _port = port; _password = password; if (isConnected()) { throw new IOException("The PircBot is already connected to an IRC server. Disconnect first."); } // Don't clear the outqueue - there might be something important in it! // Clear everything we may have know about channels. this.removeAllChannels(); // Connect to the server. Socket socket = new Socket(hostname, port); logger.info("*** Connected to server."); _inetAddress = socket.getLocalAddress(); _detector = new UniversalDetector(null); String defaultEncoding = null; OutputStreamWriter outputStreamWriter = null; if (getEncoding() != null) { // Assume the specified encoding is valid for this JVM. outputStreamWriter = new OutputStreamWriter(socket.getOutputStream(), getEncoding()); } else { // Otherwise, just use the JVM's default encoding. outputStreamWriter = new OutputStreamWriter(socket.getOutputStream()); } defaultEncoding = outputStreamWriter.getEncoding(); BufferedWriter bwriter = new BufferedWriter(outputStreamWriter); // Attempt to join the server. if (password != null && !password.equals("")) { OutputThread.sendRawLine(this, bwriter, "PASS " + password); } String nick = this.getName(); OutputThread.sendRawLine(this, bwriter, "NICK " + nick); OutputThread.sendRawLine(this, bwriter, "USER " + this.getLogin() + " 8 * :" + this.getVersion()); _inputThread = new InputThread(this, socket, socket.getInputStream(), bwriter, defaultEncoding); boolean connected = false; // Read stuff back from the server to see if we connected. int tries = 1; byte[] buffer = new byte[BUFFER_SIZE]; int readBytes = -1; String overflow = ""; while ((readBytes = socket.getInputStream().read(buffer)) > -1) { String encoding = detect(buffer); if (logger.isDebugEnabled()) { logger.debug("Detected encoding from IRC Server: {} (may be null)", encoding); } if (StringUtils.isBlank(encoding)) { encoding = defaultEncoding; } String decodedBuffer = new String(buffer, 0, readBytes, Charset.forName(encoding)); String[] lines = (overflow + decodedBuffer).split("\\r?\\n"); // if the buffer does not end with a \n, then maybe the last sentence is not complete // We need to save this part for the next round. if (!decodedBuffer.endsWith("\n")) { overflow = lines[lines.length - 1]; lines = ArrayUtils.remove(lines, lines.length - 1); } else { overflow = ""; } for (String line : lines) { if (StringUtils.isNotBlank(line)) { this.handleLine(line); int firstSpace = line.indexOf(" "); int secondSpace = line.indexOf(" ", firstSpace + 1); if (secondSpace >= 0) { String code = line.substring(firstSpace + 1, secondSpace); if (code.equals("004")) { // We're connected to the server. connected = true; break; } else if (code.equals("433")) { if (_autoNickChange) { tries++; nick = getName() + tries; OutputThread.sendRawLine(this, bwriter, "NICK " + nick); } else { socket.close(); _inputThread = null; throw new NickAlreadyInUseException(line); } } else if (code.equals("439")) { // No action required. } else if (code.startsWith("5") || code.startsWith("4")) { socket.close(); _inputThread = null; throw new IrcException("Could not log into the IRC server: " + line); } } this.setNick(nick); } } if (connected) { break; } } logger.info("*** Logged onto server."); // This makes the socket timeout on read operations after 5 minutes. // Maybe in some future version I will let the user change this at runtime. socket.setSoTimeout(5 * 60 * 1000); // Now start the InputThread to read all other lines from the server. _inputThread.start(); // Now start the outputThread that will be used to send all messages. if (_outputThread == null) { _outputThread = new OutputThread(this, _outQueue); _outputThread.start(); } this.onConnect(); }
From source file:Tcpbw100.java
public boolean test_mid(Protocol ctl) throws IOException { byte buff[] = new byte[8192]; Message msg = new Message(); if ((tests & TEST_MID) == TEST_MID) { /* now look for middleboxes (firewalls, NATs, and other boxes that * muck with TCP's end-to-end priciples */// w w w . jav a2s. c o m showStatus(messages.getString("middleboxTest")); results.append(messages.getString("checkingMiddleboxes") + " "); statistics.append(messages.getString("checkingMiddleboxes") + " "); emailText = messages.getString("checkingMiddleboxes") + " "; pub_status = "checkingMiddleboxes"; 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_PREPARE) { errmsg = messages.getString("mboxWrongMessage") + "\n"; if (msg.type == MSG_ERROR) { errmsg += "ERROR MSG: " + Integer.parseInt(new String(msg.body), 16) + "\n"; } return true; } int midport = Integer.parseInt(new String(msg.body)); Socket in2Socket = null; try { in2Socket = new Socket(host, midport); } catch (UnknownHostException e) { System.err.println("Don't know about host: " + host); errmsg = messages.getString("unknownServer") + "\n"; return true; } catch (IOException e) { System.err.println("Couldn't perform middlebox testing to: " + host); errmsg = messages.getString("middleboxFail") + "\n"; return true; } InputStream srvin2 = in2Socket.getInputStream(); OutputStream srvout2 = in2Socket.getOutputStream(); int largewin = 128 * 1024; in2Socket.setSoTimeout(6500); int bytes = 0; int inlth; t = System.currentTimeMillis(); pub_TimeStamp = new Date(); try { while ((inlth = srvin2.read(buff, 0, buff.length)) > 0) { bytes += inlth; pub_bytes = bytes; if ((System.currentTimeMillis() - t) > 5500) break; } } catch (IOException e) { } t = System.currentTimeMillis() - t; System.out.println(bytes + " bytes " + (8.0 * bytes) / t + " kb/s " + t / 1000 + " secs"); s2cspd = ((8.0 * bytes) / 1000) / t; 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("mboxWrongMessage") + "\n"; if (msg.type == MSG_ERROR) { errmsg += "ERROR MSG: " + Integer.parseInt(new String(msg.body), 16) + "\n"; } return true; } tmpstr2 = new String(msg.body); String tmpstr4 = Double.toString(s2cspd * 1000); System.out.println("Sending '" + tmpstr4 + "' back to server"); ctl.send_msg(TEST_MSG, tmpstr4.getBytes()); try { tmpstr2 += in2Socket.getInetAddress() + ";"; } catch (SecurityException e) { System.err.println("Unable to obtain Servers IP addresses: using " + host); errmsg = "getInetAddress() called failed\n"; tmpstr2 += host + ";"; results.append(messages.getString("lookupError") + "\n"); } System.err.println("calling in2Socket.getLocalAddress()"); try { tmpstr2 += in2Socket.getLocalAddress() + ";"; } catch (SecurityException e) { System.err.println("Unable to obtain local IP address: using 127.0.0.1"); errmsg = "getLocalAddress() call failed\n"; tmpstr2 += "127.0.0.1;"; } srvin2.close(); srvout2.close(); in2Socket.close(); 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("mboxWrongMessage"); 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.mirth.connect.plugins.dashboardstatus.DashboardConnectorStatusMonitor.java
public void updateStatus(String connectorId, ConnectorType type, Event event, Socket socket) { String stateImage = COLOR_BLACK; String stateText = STATE_UNKNOWN; boolean updateStatus = true; switch (event) { case INITIALIZED: switch (type) { case LISTENER: stateImage = COLOR_YELLOW;/*from w w w. j a v a 2 s. c o m*/ stateText = STATE_WAITING; break; case READER: stateImage = COLOR_YELLOW; stateText = STATE_IDLE; break; } break; case CONNECTED: switch (type) { case LISTENER: if (socket != null) { addConnectionToSocketSet(socket, connectorId); stateImage = COLOR_GREEN; stateText = STATE_CONNECTED + " (" + getSocketSetCount(connectorId) + ")"; } else { stateImage = COLOR_GREEN; stateText = STATE_CONNECTED; } break; case READER: stateImage = COLOR_GREEN; stateText = STATE_POLLING; break; } break; case DISCONNECTED: switch (type) { case LISTENER: if (socket != null) { removeConnectionInSocketSet(socket, connectorId); int connectedSockets = getSocketSetCount(connectorId); if (connectedSockets == 0) { stateImage = COLOR_YELLOW; stateText = STATE_WAITING; } else { stateImage = COLOR_GREEN; stateText = STATE_CONNECTED + " (" + connectedSockets + ")"; } } else { clearSocketSet(connectorId); stateImage = COLOR_RED; stateText = STATE_DISCONNECTED; } break; case READER: stateImage = COLOR_RED; stateText = STATE_NOT_POLLING; break; case WRITER: stateImage = COLOR_RED; stateText = STATE_DISCONNECTED; break; case SENDER: stateImage = COLOR_RED; stateText = STATE_DISCONNECTED; break; } break; case BUSY: switch (type) { case READER: stateImage = COLOR_GREEN; stateText = STATE_READING; break; case LISTENER: stateImage = COLOR_GREEN; stateText = STATE_RECEIVING; break; case WRITER: stateImage = COLOR_YELLOW; stateText = STATE_WRITING; break; case SENDER: stateImage = COLOR_YELLOW; stateText = STATE_SENDING; break; } break; case DONE: switch (type) { case READER: stateImage = COLOR_YELLOW; stateText = STATE_IDLE; break; case LISTENER: if (socket != null) { stateImage = COLOR_GREEN; stateText = STATE_CONNECTED + " (" + getSocketSetCount(connectorId) + ")"; } else { stateImage = COLOR_YELLOW; stateText = STATE_WAITING; } break; } break; case ATTEMPTING: switch (type) { case WRITER: stateImage = COLOR_YELLOW; stateText = STATE_ATTEMPTING; break; case SENDER: stateImage = COLOR_YELLOW; stateText = STATE_ATTEMPTING; break; } break; default: updateStatus = false; break; } if (updateStatus) { Timestamp timestamp = new Timestamp(System.currentTimeMillis()); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS"); String channelName = ""; // this will be overwritten down below. If not, something's wrong. String connectorType = type.toString(); String information = ""; /* * check 'connectorId' - contains destination_1_connector, etc. * connectorId consists of id_source_connector for sources, and * id_destination_x_connector for destinations. i.e. tokenCount will * be 3 for sources and 4 for destinations. Note that READER and * LISTENER are sources, and WRITER and SENDER are destinations. */ StringTokenizer tokenizer = new StringTokenizer(connectorId, "_"); String channelId = tokenizer.nextToken(); int destinationIndex; LinkedList<String[]> channelLog = null; Channel channel = ControllerFactory.getFactory().createChannelController() .getDeployedChannelById(channelId); if (channel != null) { channelName = channel.getName(); // grab the channel's log from the HashMap, if not exist, create // one. if (connectorInfoLogs.containsKey(channelName)) { channelLog = connectorInfoLogs.get(channelName); } else { channelLog = new LinkedList<String[]>(); } Connector connector = null; switch (type) { case READER: connectorType = "Source: " + channel.getSourceConnector().getTransportName() + " (" + channel.getSourceConnector().getTransformer().getInboundProtocol().toString() + " -> " + channel.getSourceConnector().getTransformer().getOutboundProtocol().toString() + ")"; break; case LISTENER: connectorType = "Source: " + channel.getSourceConnector().getTransportName() + " (" + channel.getSourceConnector().getTransformer().getInboundProtocol().toString() + " -> " + channel.getSourceConnector().getTransformer().getOutboundProtocol().toString() + ")"; break; case WRITER: tokenizer.nextToken(); // destinationId begins from 1, so subtract by 1 for the // arrayIndex. destinationIndex = Integer.valueOf(tokenizer.nextToken()) - 1; connector = channel.getDestinationConnectors().get(destinationIndex); connectorType = "Destination: " + connector.getTransportName() + " - " + connector.getName(); if (connector.getTransportName().equals(FileWriterProperties.name)) { // Destination - File Writer. switch (event) { case BUSY: information = FileWriterProperties.getInformation(connector.getProperties()); break; } } else if (connector.getTransportName().equals(DatabaseWriterProperties.name)) { // Destination - Database Writer. information = DatabaseWriterProperties.getInformation(connector.getProperties()); } else if (connector.getTransportName().equals(JMSWriterProperties.name)) { // Destination - JMS Writer. information = JMSWriterProperties.getInformation(connector.getProperties()); } else if (connector.getTransportName().equals(DocumentWriterProperties.name)) { // Destination - Document Writer. information = DocumentWriterProperties.getInformation(connector.getProperties()); } break; case SENDER: tokenizer.nextToken(); // destinationId begins from 1, so subtract by 1 for the // arrayIndex. destinationIndex = Integer.valueOf(tokenizer.nextToken()) - 1; connector = channel.getDestinationConnectors().get(destinationIndex); connectorType = "Destination: " + connector.getTransportName() + " - " + connector.getName(); if (connector.getTransportName().equals(HttpSenderProperties.name)) { // Destination - HTTP Sender. information = HttpSenderProperties.getInformation(connector.getProperties()); } else if (connector.getTransportName().equals(ChannelWriterProperties.name)) { // Destination - Channel Writer. Channel targetChannel = ControllerFactory.getFactory().createChannelController() .getDeployedChannelById( ChannelWriterProperties.getInformation(connector.getProperties())); if (targetChannel == null) { information = "Target Channel: None"; } else { information = "Target Channel: " + targetChannel.getName(); } } else if (connector.getTransportName().equals(SmtpSenderProperties.name)) { // Destination - SMTP Sender. information = SmtpSenderProperties.getInformation(connector.getProperties()); } else if (connector.getTransportName().equals(TCPSenderProperties.name)) { // Destination - TCP Sender. // The useful info for TCP Sender - host:port will // be taken care of by the socket below. } else if (connector.getTransportName().equals(LLPSenderProperties.name)) { // Destination - LLP Sender. // The useful info for LLP Sender - host:port will // be taken care of by the socket below. } else if (connector.getTransportName().equals(WebServiceSenderProperties.name)) { // Destination - Web Service Sender. // information = ""; } break; } } if (socket != null) { String sendingAddress = socket.getLocalAddress().toString() + ":" + socket.getLocalPort(); String receivingAddress = socket.getInetAddress().toString() + ":" + socket.getPort(); // If addresses begin with a slash "/", remove it. if (sendingAddress.startsWith("/")) { sendingAddress = sendingAddress.substring(1); } if (receivingAddress.startsWith("/")) { receivingAddress = receivingAddress.substring(1); } information += "Sender: " + sendingAddress + " Receiver: " + receivingAddress; } if (channelLog != null) { synchronized (this) { if (channelLog.size() == MAX_LOG_SIZE) { channelLog.removeLast(); } channelLog.addFirst(new String[] { String.valueOf(logId), channelName, dateFormat.format(timestamp), connectorType, event.toString(), information }); if (entireConnectorInfoLogs.size() == MAX_LOG_SIZE) { entireConnectorInfoLogs.removeLast(); } entireConnectorInfoLogs.addFirst(new String[] { String.valueOf(logId), channelName, dateFormat.format(timestamp), connectorType, event.toString(), information }); logId++; // put the channel log into the HashMap. connectorInfoLogs.put(channelName, channelLog); } } connectorStateMap.put(connectorId, new String[] { stateImage, stateText }); } }