List of usage examples for java.net Socket getRemoteSocketAddress
public SocketAddress getRemoteSocketAddress()
From source file:com.lithium.flow.shell.sshj.SshjTunnel.java
private void accept(@Nonnull Socket socket) throws IOException { log.debug("connection from {}", socket.getRemoteSocketAddress()); AbstractDirectChannel channel = new AbstractDirectChannel(connection, "direct-tcpip") { @Override// w w w .ja v a 2s. c o m @Nonnull protected SSHPacket buildOpenReq() { return super.buildOpenReq().putString(tunneling.getHost()).putUInt32(tunneling.getPort()) .putString(getHost()).putUInt32(server.getLocalPort()); } }; channel.open(); socket.setSendBufferSize(channel.getLocalMaxPacketSize()); socket.setReceiveBufferSize(channel.getRemoteMaxPacketSize()); Event<IOException> soc2chan = new StreamCopier(socket.getInputStream(), channel.getOutputStream()) .bufSize(channel.getRemoteMaxPacketSize()).spawnDaemon("soc2chan"); Event<IOException> chan2soc = new StreamCopier(channel.getInputStream(), socket.getOutputStream()) .bufSize(channel.getLocalMaxPacketSize()).spawnDaemon("chan2soc"); SocketStreamCopyMonitor.monitor(5, TimeUnit.SECONDS, soc2chan, chan2soc, channel, socket); }
From source file:net.timewalker.ffmq4.transport.tcp.io.TcpPacketTransport.java
@Override public SocketAddress getRemotePeer() { Socket sock = socket; return sock != null ? sock.getRemoteSocketAddress() : null; }
From source file:org.openhealthtools.common.ws.server.IheConnectionListener.java
public void run() { try {/*from w w w . j a va 2 s . c om*/ while (!Thread.interrupted()) { try { // if (serversocket == null || serversocket.isClosed()) { // serversocket = new ServerSocket(port); // serversocket.setReuseAddress(true); if (LOG.isInfoEnabled()) { LOG.info("Listening on port " + this.serversocket.getLocalPort()); } // } LOG.debug("Waiting for incoming HTTP connection"); Socket socket = this.serversocket.accept(); if (LOG.isDebugEnabled()) { LOG.debug("Incoming HTTP connection from " + socket.getRemoteSocketAddress()); } AxisHttpConnection conn = new AxisHttpConnectionImpl(socket, this.params); this.connmanager.process(conn); } catch (java.io.InterruptedIOException ie) { break; } catch (Throwable ex) { if (Thread.interrupted()) { break; } if (!failureHandler.failed(this, ex)) { break; } } } } finally { destroy(); } }
From source file:org.apache.axis2.transport.testkit.util.tcpmon.Relay.java
public Relay(Socket inSocket, Socket outSocket, boolean isResponse) throws IOException { this.inSocket = inSocket; this.in = inSocket.getInputStream(); this.out = outSocket.getOutputStream(); if (isResponse) { connectionSpec = outSocket.getRemoteSocketAddress() + " <- " + inSocket.getRemoteSocketAddress(); } else {/*from w w w . j a va 2 s.c o m*/ connectionSpec = inSocket.getRemoteSocketAddress() + " -> " + outSocket.getRemoteSocketAddress(); } }
From source file:org.apache.axis2.transport.http.server.DefaultConnectionListener.java
public void run() { try {//from w w w. j a v a2 s .c o m while (!Thread.interrupted()) { try { if (serversocket == null || serversocket.isClosed()) { if (LOG.isInfoEnabled()) { LOG.info("Listening on port " + port); } serversocket = new ServerSocket(port); serversocket.setReuseAddress(true); } LOG.debug("Waiting for incoming HTTP connection"); Socket socket = this.serversocket.accept(); if (LOG.isDebugEnabled()) { LOG.debug("Incoming HTTP connection from " + socket.getRemoteSocketAddress()); } AxisHttpConnection conn = new AxisHttpConnectionImpl(socket, this.params); try { this.connmanager.process(conn); } catch (RejectedExecutionException e) { conn.sendResponse(new DefaultHttpResponseFactory().newHttpResponse(HttpVersion.HTTP_1_0, HttpStatus.SC_SERVICE_UNAVAILABLE, new BasicHttpContext(null))); } } catch (java.io.InterruptedIOException ie) { break; } catch (Throwable ex) { if (Thread.interrupted()) { break; } if (!failureHandler.failed(this, ex)) { break; } } } } finally { destroy(); } }
From source file:edu.umass.cs.msocket.common.policies.GeolocationProxyPolicy.java
@Override public List<String> getProxyIPs(List<ProxyStatusInfo> proxies, Socket acceptedSocket) { final SocketAddress remoteIp = acceptedSocket.getRemoteSocketAddress(); double clientLatitude = 0; double clientLongitude = 0; try {/*w w w . j a v a2 s.c om*/ // Contact http://freegeoip.net/csv/[IP] to resolve IP address location URL locator = new URL("http://freegeoip.net/csv/" + remoteIp); BufferedReader in = new BufferedReader(new InputStreamReader(locator.openStream())); String csv = in.readLine(); in.close(); // Read location result StringTokenizer st = new StringTokenizer(csv, ","); if (!st.hasMoreTokens()) throw new IOException("Failed to read IP"); st.nextToken(); // IP if (!st.hasMoreTokens()) throw new IOException("Failed to read country code"); st.nextToken(); // country code if (!st.hasMoreTokens()) throw new IOException("Failed to read country name"); st.nextToken(); // country name if (!st.hasMoreTokens()) throw new IOException("Failed to read state code"); st.nextToken(); // state code if (!st.hasMoreTokens()) throw new IOException("Failed to read state name"); st.nextToken(); // state name if (!st.hasMoreTokens()) throw new IOException("Failed to read city"); st.nextToken(); // city if (!st.hasMoreTokens()) throw new IOException("Failed to read zip"); st.nextToken(); // zip if (!st.hasMoreTokens()) throw new IOException("Failed to read latitude"); String latitudeStr = st.nextToken().replace("\"", ""); clientLatitude = Double.parseDouble(latitudeStr); if (!st.hasMoreTokens()) throw new IOException("Failed to read longitude"); String longitudeStr = st.nextToken().replace("\"", ""); clientLongitude = Double.parseDouble(longitudeStr); } catch (Exception e) { logger.log(Level.WARNING, "Failed to geolocate IP address " + remoteIp, e); } // Compute the distance with each proxy Map<Double, ProxyStatusInfo> distances = new HashMap<Double, ProxyStatusInfo>(); for (ProxyStatusInfo proxyStatusInfo : proxies) { double distance = GeodeticCalculator .calculateGeodeticMeasurement(new GlobalPosition(clientLatitude, clientLongitude, 0), new GlobalPosition(proxyStatusInfo.getLatitude(), proxyStatusInfo.getLontitude(), 0)) .getPointToPointDistance(); distances.put(distance, proxyStatusInfo); } // Build the result list List<String> ipPorts = new LinkedList<String>(); int proxiesLeft = numProxies; while (proxiesLeft > 0 && !distances.isEmpty()) { // Set of keys is ordered so just take the first one and send it ProxyStatusInfo proxy = distances.remove(distances.keySet().iterator().next()); ipPorts.add(proxy.getIp()); } return ipPorts; }
From source file:edu.umass.cs.msocket.common.policies.GeoLoadProxyPolicy.java
@Override public List<String> getProxyIPs(List<ProxyStatusInfo> proxies, Socket acceptedSocket) { final SocketAddress remoteIp = acceptedSocket.getRemoteSocketAddress(); double clientLatitude = 0; double clientLongitude = 0; try {/* w w w. j a v a2 s .c o m*/ // Contact http://freegeoip.net/csv/[IP] to resolve IP address location URL locator = new URL("http://freegeoip.net/csv/" + remoteIp); BufferedReader in = new BufferedReader(new InputStreamReader(locator.openStream())); String csv = in.readLine(); in.close(); // Read location result StringTokenizer st = new StringTokenizer(csv, ","); if (!st.hasMoreTokens()) throw new IOException("Failed to read IP"); st.nextToken(); // IP if (!st.hasMoreTokens()) throw new IOException("Failed to read country code"); st.nextToken(); // country code if (!st.hasMoreTokens()) throw new IOException("Failed to read country name"); st.nextToken(); // country name if (!st.hasMoreTokens()) throw new IOException("Failed to read state code"); st.nextToken(); // state code if (!st.hasMoreTokens()) throw new IOException("Failed to read state name"); st.nextToken(); // state name if (!st.hasMoreTokens()) throw new IOException("Failed to read city"); st.nextToken(); // city if (!st.hasMoreTokens()) throw new IOException("Failed to read zip"); st.nextToken(); // zip if (!st.hasMoreTokens()) throw new IOException("Failed to read latitude"); String latitudeStr = st.nextToken().replace("\"", ""); clientLatitude = Double.parseDouble(latitudeStr); if (!st.hasMoreTokens()) throw new IOException("Failed to read longitude"); String longitudeStr = st.nextToken().replace("\"", ""); clientLongitude = Double.parseDouble(longitudeStr); } catch (Exception e) { logger.log(Level.WARNING, "Failed to geolocate IP address " + remoteIp, e); } // Compute the distance with each proxy and check the load Map<Double, ProxyStatusInfo> distances = new HashMap<Double, ProxyStatusInfo>(); for (ProxyStatusInfo proxyStatusInfo : proxies) { // Ignore proxies that have more than the max defined in the policy try { if (ProxyLoadStatistics.getOpenTcpConnFromSerializedInfo(proxyStatusInfo.getLoad()) > maxTCPConn || ProxyLoadStatistics .getThroughputFromSerializedInfo(proxyStatusInfo.getLoad()) > maxThroughput) continue; } catch (JSONException e) { logger.warning("Unable to get load information from proxy " + proxyStatusInfo.getGuid() + ": " + e); } double distance = GeodeticCalculator .calculateGeodeticMeasurement(new GlobalPosition(clientLatitude, clientLongitude, 0), new GlobalPosition(proxyStatusInfo.getLatitude(), proxyStatusInfo.getLontitude(), 0)) .getPointToPointDistance(); distances.put(distance, proxyStatusInfo); } // Build the result list List<String> ipPorts = new LinkedList<String>(); int proxiesLeft = numProxies; while (proxiesLeft > 0 && !distances.isEmpty()) { // Set of keys is ordered so just take the first one and send it ProxyStatusInfo proxy = distances.remove(distances.keySet().iterator().next()); ipPorts.add(proxy.getIp()); } return ipPorts; }
From source file:org.fourthline.cling.transport.impl.apache.StreamServerImpl.java
protected boolean isConnectionOpen(Socket socket, byte[] heartbeat) { if (log.isLoggable(Level.FINE)) log.fine("Checking if client connection is still open on: " + socket.getRemoteSocketAddress()); try {/*from w w w. ja v a 2s . com*/ socket.getOutputStream().write(heartbeat); socket.getOutputStream().flush(); return true; } catch (IOException ex) { if (log.isLoggable(Level.FINE)) log.fine("Client connection has been closed: " + socket.getRemoteSocketAddress()); return false; } }
From source file:och.util.socket.json.server.JsonProtocolSocketHandler.java
@Override public void process(Socket openedSocket, InputStream socketIn, OutputStream socketOut, SocketServer owner) throws Throwable { SocketAddress remoteAddress = openedSocket.getRemoteSocketAddress(); BufferedReader reader = SocketUtil.getReaderUTF8(socketIn); BufferedOutputStream os = new BufferedOutputStream(socketOut); while (!owner.wasShutdown()) { String line = reader.readLine(); if (line == null || owner.wasShutdown()) break; //process req try {//from w ww. ja v a 2 s .c om try { line = secureProvider.decode(line); } catch (Throwable t) { throw new InvalidReqException("decode exception: " + t.getMessage()); } if (!line.startsWith(PROTOCOL_PREFIX)) throw new InvalidReqException("unknown protocol: " + line); String data = line.substring(PROTOCOL_PREFIX.length()); int typeSepIndex = data.indexOf(':'); if (typeSepIndex < 1) throw new InvalidReqException("no data type in req: " + line); String typeStr = data.substring(0, typeSepIndex); Class<?> type = null; try { type = Class.forName(typeStr); } catch (Exception e) { throw new InvalidReqException("not java class: " + typeStr); } ReqController<? super Object, ?> controller = controllers.get(type); if (controller == null) throw new InvalidReqException("no controller for type: " + type); Object req = null; try { String jsonReq = data.substring(typeSepIndex + 1); if (hasText(jsonReq)) req = defaultGson.fromJson(jsonReq, type); } catch (Exception e) { throw new InvalidReqException("invalid json data in req: " + data); } //process Object resp = controller.processReq(req, remoteAddress); //send resp String jsonResp = resp == null ? "" : defaultGson.toJson(resp); writeLine(os, OK + controller.respType + ":" + jsonResp); os.flush(); } catch (Exception e) { //connection closed if (e instanceof SocketException) throw e; //validation error else if (e instanceof ValidationException) sendAndFlush(os, validationError((ValidationException) e)); //unexpected error else { log.error("unexpected exception: ", e); sendAndFlush(os, UNEXPECTED_ERROR + e); } } } }
From source file:immf.MyWiser.java
/** * Create a new SMTP server with this class as the listener. * The default port is 25. Call setPort()/setHostname() before * calling start().//w ww . j a va 2 s . c o m */ public MyWiser(UsernamePasswordValidator userPass, int port, MyWiserMailListener listener, final String tlsKeyStore, final String tlsKeyType, final String tlsKeyPasswd) { if (tlsKeyStore == null) { log.info("SMTP Server disable TLS"); this.server = new SMTPServer(this, new EasyAuthenticationHandlerFactory(userPass)); this.server.setHideTLS(true); // TLS? } else { // TLS log.info("SMTP Server enable TLS"); this.server = new SMTPServer(this, new EasyAuthenticationHandlerFactory(userPass)) { public SSLSocket createSSLSocket(Socket socket) throws IOException { SSLSocketFactory sf = createSslSocketFactory(tlsKeyStore, tlsKeyType, tlsKeyPasswd); InetSocketAddress remoteAddress = (InetSocketAddress) socket.getRemoteSocketAddress(); SSLSocket s = (SSLSocket) (sf.createSocket(socket, remoteAddress.getHostName(), socket.getPort(), true)); s.setUseClientMode(false); s.setEnabledCipherSuites(s.getSupportedCipherSuites()); return s; } }; this.server.setRequireTLS(true); // TLS } this.server.setPort(port); this.listener = listener; }