Java Code Examples for java.nio.channels.SocketChannel#getRemoteAddress()

The following examples show how to use java.nio.channels.SocketChannel#getRemoteAddress() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AsyncNodeMessageHandler.java    From JPPF with Apache License 2.0 6 votes vote down vote up
/**
 * Compute a repeatable unique identifier for a node, which can be reused over node restarts.
 * @param factory bundler (load-balancer) factory.
 * @param channel the channel that carries the host information.
 * @param info the system information for the node.
 * @return a pair of string representing the clear string (keft side) and resulting unique string identifier for the node (right side).
 * @throws Exception if any error occurs.
 */
private static Pair<String, String> getNodeIdentifier(final JPPFBundlerFactory factory, final BaseNodeContext channel, final JPPFSystemInformation info) throws Exception {
  if (factory.getPersistence() == null) return null;
  final StringBuilder sb = new StringBuilder();
  final String ip = NetworkUtils.getNonLocalHostAddress();
  sb.append('[').append(ip == null ? "localhost" : ip);
  if (channel.getSocketChannel() != null) {
    final SocketChannel ch = channel.getSocketChannel();
    sb.append(':').append(ch.socket().getLocalPort()).append(']');
    final InetSocketAddress isa = (InetSocketAddress) ch.getRemoteAddress();
    sb.append(isa.getAddress().getHostAddress());
  } else if (channel.isLocal()) {
    sb.append( "local_channel").append(']');
  }
  final TypedProperties jppf = info.getJppf();
  final boolean master = jppf.get(JPPFProperties.PROVISIONING_MASTER);
  final boolean slave = jppf.get(JPPFProperties.PROVISIONING_SLAVE);
  if (master || slave) {
    sb.append(master ? "master" : "slave");
    sb.append(jppf.get(JPPFProperties.PROVISIONING_SLAVE_PATH_PREFIX));
    if (slave) sb.append(jppf.get(JPPFProperties.PROVISIONING_SLAVE_ID));
  }
  final String s = sb.toString();
  return new Pair<>(s, CryptoUtils.computeHash(s, factory.getHashAlgorithm()));
}
 
Example 2
Source File: SSLSocketChannel.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
public SSLSocketChannel(final SSLContext sslContext, final SocketChannel socketChannel, final boolean client) throws IOException {
    if (!socketChannel.isConnected()) {
        throw new IllegalArgumentException("Cannot pass an un-connected SocketChannel");
    }

    this.channel = socketChannel;

    this.socketAddress = socketChannel.getRemoteAddress();
    final Socket socket = socketChannel.socket();
    this.hostname = socket.getInetAddress().getHostName();
    this.port = socket.getPort();

    this.engine = sslContext.createSSLEngine();
    this.engine.setUseClientMode(client);
    this.engine.setNeedClientAuth(true);

    streamInManager = new BufferStateManager(ByteBuffer.allocate(engine.getSession().getPacketBufferSize()));
    streamOutManager = new BufferStateManager(ByteBuffer.allocate(engine.getSession().getPacketBufferSize()));
    appDataManager = new BufferStateManager(ByteBuffer.allocate(engine.getSession().getApplicationBufferSize()));
}
 
Example 3
Source File: SSLSocketChannel.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
public SSLSocketChannel(final SSLEngine sslEngine, final SocketChannel socketChannel) throws IOException {
    if (!socketChannel.isConnected()) {
        throw new IllegalArgumentException("Cannot pass an un-connected SocketChannel");
    }

    this.channel = socketChannel;

    this.socketAddress = socketChannel.getRemoteAddress();
    final Socket socket = socketChannel.socket();
    this.hostname = socket.getInetAddress().getHostName();
    this.port = socket.getPort();

    // don't set useClientMode or needClientAuth, use the engine as is and let the caller configure it
    this.engine = sslEngine;

    streamInManager = new BufferStateManager(ByteBuffer.allocate(engine.getSession().getPacketBufferSize()));
    streamOutManager = new BufferStateManager(ByteBuffer.allocate(engine.getSession().getPacketBufferSize()));
    appDataManager = new BufferStateManager(ByteBuffer.allocate(engine.getSession().getApplicationBufferSize()));
}
 
Example 4
Source File: MysqlChannel.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
public MysqlChannel(SocketChannel channel) {
    this.sequenceId = 0;
    this.channel = channel;
    this.sendBuffer = ByteBuffer.allocate(2 * 1024 * 1024);
    this.isSend = false;

    // get remote description
    try {
        if (channel.getRemoteAddress() instanceof InetSocketAddress) {
            InetSocketAddress address = (InetSocketAddress) channel.getRemoteAddress();
            remote = address.getAddress().getHostAddress() + ":" + address.getPort();
        } else {
            // Reach here, what's it?
            remote = channel.getRemoteAddress().toString();
        }
    } catch (Exception e) {
        remote = "";
    }
}
 
Example 5
Source File: SocketChannelWrapperBar.java    From baratine with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns the server inet address that accepted the request.
 */
@Override
public InetSocketAddress ipRemote()
{
  SocketChannel s = _channel;
  
  if (s != null) {
    try {
      return (InetSocketAddress) s.getRemoteAddress();
    } catch (IOException e) {
      return null;
      //throw new RuntimeException(e);
    }
  }
  else {
    return null;
  }
}
 
Example 6
Source File: SocketChannelWrapperBar.java    From baratine with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns the remote client's inet address.
 */
@Override
public InetAddress addressRemote()
{
  SocketChannel s = _channel;
  
  if (s != null) {
    try {
      InetSocketAddress addr = (InetSocketAddress) s.getRemoteAddress();
      
      return addr.getAddress();
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
  else {
    return null;
  }
}
 
Example 7
Source File: NIOAcceptor.java    From Mycat-NIO with Apache License 2.0 6 votes vote down vote up
/**
 * 接受新连接
 */
private void accept() {
	SocketChannel channel = null;
	try {
		channel = serverChannel.accept();
		channel.configureBlocking(false);
		Connection c = factory.make(channel);
		c.setDirection(Connection.Direction.in);
		c.setId(ConnectIdGenerator.getINSTNCE().getId());
		InetSocketAddress remoteAddr = (InetSocketAddress) channel
				.getRemoteAddress();
		c.setHost(remoteAddr.getHostString());
		c.setPort(remoteAddr.getPort());
		// 派发此连接到某个Reactor处理
		NIOReactor reactor = reactorPool.getNextReactor();
		reactor.postRegister(c);

	} catch (Throwable e) {
		closeChannel(channel);
		LOGGER.warn(getName(), e);
	}
}
 
Example 8
Source File: SSLSocketChannel.java    From nifi with Apache License 2.0 6 votes vote down vote up
public SSLSocketChannel(final SSLContext sslContext, final SocketChannel socketChannel, final boolean client) throws IOException {
    if (!socketChannel.isConnected()) {
        throw new IllegalArgumentException("Cannot pass an un-connected SocketChannel");
    }

    this.channel = socketChannel;

    this.socketAddress = socketChannel.getRemoteAddress();
    final Socket socket = socketChannel.socket();
    this.hostname = socket.getInetAddress().getHostName();
    this.port = socket.getPort();

    this.engine = sslContext.createSSLEngine();
    this.engine.setUseClientMode(client);
    this.engine.setNeedClientAuth(true);

    streamInManager = new BufferStateManager(ByteBuffer.allocate(engine.getSession().getPacketBufferSize()));
    streamOutManager = new BufferStateManager(ByteBuffer.allocate(engine.getSession().getPacketBufferSize()));
    appDataManager = new BufferStateManager(ByteBuffer.allocate(engine.getSession().getApplicationBufferSize()));
}
 
Example 9
Source File: SSLSocketChannel.java    From nifi with Apache License 2.0 6 votes vote down vote up
public SSLSocketChannel(final SSLEngine sslEngine, final SocketChannel socketChannel) throws IOException {
    if (!socketChannel.isConnected()) {
        throw new IllegalArgumentException("Cannot pass an un-connected SocketChannel");
    }

    this.channel = socketChannel;

    this.socketAddress = socketChannel.getRemoteAddress();
    final Socket socket = socketChannel.socket();
    this.hostname = socket.getInetAddress().getHostName();
    this.port = socket.getPort();

    // don't set useClientMode or needClientAuth, use the engine as is and let the caller configure it
    this.engine = sslEngine;

    streamInManager = new BufferStateManager(ByteBuffer.allocate(engine.getSession().getPacketBufferSize()));
    streamOutManager = new BufferStateManager(ByteBuffer.allocate(engine.getSession().getPacketBufferSize()));
    appDataManager = new BufferStateManager(ByteBuffer.allocate(engine.getSession().getApplicationBufferSize()));
}
 
Example 10
Source File: NIOAcceptor.java    From feeyo-redisproxy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * 接受新连接
 */
private void accept() {
	SocketChannel channel = null;
	try {
		channel = serverChannel.accept();			
		channel.configureBlocking( false );
		
		// 设置QOS
		// 低成本:0x02 (二进制的倒数第二位为1)
		// 高可靠性:0x04(二进制的倒数第三位为1)
		// 最高吞吐量:0x08(二进制的倒数第四位为1)
		// 最小延迟:0x10(二进制的倒数第五位为1)
		//channel.socket().setTrafficClass( 0x04 | 0x08 ); 	
		
		
		
		// 构建 Connection
		ClosableConnection c = factory.make(channel);
		c.setDirection( ClosableConnection.Direction.in );
		//c.setId( ConnectIdGenerator.getINSTNCE().getId() );
		
		InetSocketAddress remoteAddr = (InetSocketAddress) channel.getRemoteAddress();
		c.setHost(remoteAddr.getHostString());
		c.setPort(remoteAddr.getPort());
		
		// 将新连接派发至reactor进行异步处理
		NIOReactor reactor = reactorPool.getNextReactor();
		reactor.postRegister(c);

	} catch (Exception e) {
		LOGGER.warn(getName(), e);
		closeChannel(channel);
	}
}
 
Example 11
Source File: TcpPair.java    From netcrusher-java with Apache License 2.0 5 votes vote down vote up
TcpPair(
    NioReactor reactor,
    TcpFilters filters,
    SocketChannel inner,
    SocketChannel outer,
    BufferOptions bufferOptions,
    Runnable ownerClose) throws IOException
{
    this.ownerClose = ownerClose;
    this.reactor = reactor;

    this.clientAddress = (InetSocketAddress) inner.getRemoteAddress();

    TcpQueue innerToOuter = TcpQueue.allocateQueue(clientAddress, bufferOptions,
        filters.getOutgoingTransformFilterFactory(), filters.getOutgoingThrottlerFactory());
    TcpQueue outerToInner = TcpQueue.allocateQueue(clientAddress, bufferOptions,
        filters.getIncomingTransformFilterFactory(), filters.getIncomingThrottlerFactory());

    this.innerChannel = new TcpChannel("INNER", reactor, this::closeAll, inner,
        outerToInner, innerToOuter);
    this.outerChannel = new TcpChannel("OUTER", reactor, this::closeAll, outer,
        innerToOuter, outerToInner);

    this.innerChannel.setOther(outerChannel);
    this.outerChannel.setOther(innerChannel);

    this.state = new State(State.FROZEN);
}
 
Example 12
Source File: SimpleSocketWorker.java    From antsdb with GNU Lesser General Public License v3.0 5 votes vote down vote up
public SimpleSocketWorker(SaltedFish fish, SocketChannel channel) {
    this.buf.order(ByteOrder.LITTLE_ENDIAN);
    this.fish = fish;
    this.channel = channel;
    this.out = new ChannelWriterNio(channel);
    SocketAddress remote = null;
    try {
        remote = channel.getRemoteAddress();
    }
    catch (IOException x) {
        _log.warn("something is wrong", x);
    }
    this.mysession = new MysqlSession(fish, out, remote);
}
 
Example 13
Source File: AcceptorImpl.java    From qpid-proton-j with Apache License 2.0 4 votes vote down vote up
@Override
public void run(Selectable selectable) {
    Reactor reactor = selectable.getReactor();
    try {
        SocketChannel socketChannel = ((ServerSocketChannel)selectable.getChannel()).accept();
        if (socketChannel == null) {
            throw new ReactorInternalException("Selectable readable, but no socket to accept");
        }
        Handler handler = BaseHandler.getHandler(AcceptorImpl.this);
        if (handler == null) {
            handler = reactor.getHandler();
        }
        Connection conn = reactor.connection(handler);
        Record conn_recs = conn.attachments();
        conn_recs.set(CONNECTION_ACCEPTOR_KEY, Acceptor.class, AcceptorImpl.this);
        InetSocketAddress peerAddr = (InetSocketAddress)socketChannel.getRemoteAddress();
        if (peerAddr != null) {
            Address addr = new Address();
            addr.setHost(peerAddr.getHostString());
            addr.setPort(Integer.toString(peerAddr.getPort()));
            conn_recs.set(ReactorImpl.CONNECTION_PEER_ADDRESS_KEY, Address.class, addr);
        }
        Transport trans = Proton.transport();

        int maxFrameSizeOption = reactor.getOptions().getMaxFrameSize();
        if (maxFrameSizeOption != 0) {
            trans.setMaxFrameSize(maxFrameSizeOption);
        }

        if(reactor.getOptions().isEnableSaslByDefault()) {
            Sasl sasl = trans.sasl();
            sasl.server();
            sasl.setMechanisms("ANONYMOUS");
            sasl.done(SaslOutcome.PN_SASL_OK);
        }
        trans.bind(conn);
        IOHandler.selectableTransport(reactor, socketChannel.socket(), trans);
    } catch(IOException ioException) {
        sel.error();
    }
}
 
Example 14
Source File: NetworkHandler.java    From RipplePower with Apache License 2.0 4 votes vote down vote up
/**
 * Processes an OP_ACCEPT selection event
 *
 * We will accept the connection if we haven't reached the maximum number of
 * connections. The new socket channel will be placed in non-blocking mode
 * and the selection key enabled for read events. We will not add the peer
 * address to the peer address list since we only want nodes that have
 * advertised their availability on the list.
 */
private void processAccept(SelectionKey acceptKey) {
	try {
		SocketChannel channel = listenChannel.accept();
		if (channel != null) {
			InetSocketAddress remoteAddress = (InetSocketAddress) channel.getRemoteAddress();
			PeerAddress address = new PeerAddress(remoteAddress);
			if (connections.size() >= maxConnections) {
				channel.close();
				BTCLoader.info(String.format("Max connections reached: Connection rejected from %s", address));
			} else if (isBlacklisted(address.getAddress())) {
				channel.close();
				BTCLoader.info(String.format("Connection rejected from banned address %s", address));
			} else if (connectionMap.get(address.getAddress()) != null) {
				channel.close();
				BTCLoader.info(String.format("Duplicate connection rejected from %s", address));
			} else {
				address.setTimeConnected(System.currentTimeMillis() / 1000);
				channel.configureBlocking(false);
				channel.setOption(StandardSocketOptions.SO_KEEPALIVE, true);
				SelectionKey key = channel.register(networkSelector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);
				Peer peer = new Peer(address, channel, key);
				key.attach(peer);
				peer.setConnected(true);
				address.setConnected(true);
				BTCLoader.info(String.format("Connection accepted from %s", address));
				Message msg = VersionMessage.buildVersionMessage(peer, BTCLoader.listenAddress,
						BTCLoader.blockStore.getChainHeight());
				synchronized (connections) {
					connections.add(peer);
					connectionMap.put(address.getAddress(), peer);
					peer.getOutputList().add(msg);
				}
				BTCLoader.info(String.format("Sent 'version' message to %s", address));
			}
		}
	} catch (IOException exc) {
		BTCLoader.error("Unable to accept connection", exc);
		networkShutdown = true;
	}
}