Java Code Examples for java.net.InetSocketAddress#getHostString()

The following examples show how to use java.net.InetSocketAddress#getHostString() . These examples are extracted from open source projects. 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 Project: reactor-netty   File: UdpMetricsTests.java    License: Apache License 2.0 6 votes vote down vote up
private void checkExpectationsPositive() {
	InetSocketAddress sa = (InetSocketAddress) serverConnection.channel().localAddress();
	String serverAddress = sa.getHostString() + ":" + sa.getPort();
	InetSocketAddress ca = (InetSocketAddress) clientConnection.channel().localAddress();
	String clientAddress = ca.getHostString() + ":" + ca.getPort();
	String[] timerTags = new String[] {REMOTE_ADDRESS, serverAddress, STATUS, "SUCCESS"};
	String[] summaryTags1 = new String[] {REMOTE_ADDRESS, clientAddress, URI, "udp"};
	String[] summaryTags2 = new String[] {REMOTE_ADDRESS, serverAddress, URI, "udp"};

	checkDistributionSummary(SERVER_DATA_SENT, summaryTags1);
	checkDistributionSummary(SERVER_DATA_RECEIVED, summaryTags1);
	checkCounter(SERVER_ERRORS, summaryTags1, false);

	checkClientConnectTime(timerTags);
	checkDistributionSummary(CLIENT_DATA_SENT, summaryTags2);
	checkDistributionSummary(CLIENT_DATA_RECEIVED, summaryTags2);
	checkCounter(CLIENT_ERRORS, summaryTags2, false);
}
 
Example 2
/**
 * Resolves a hostname via remote DNS over socks5 proxy.
 */
@Nullable
public static InetSocketAddress lookup(Socks5Proxy proxy, InetSocketAddress addr) {
    if (!addr.isUnresolved()) {
        return addr;
    }
    try {
        SocksSocket proxySocket = new SocksSocket(proxy, addr.getHostString(), addr.getPort());
        InetAddress addrResolved = proxySocket.getInetAddress();
        proxySocket.close();
        if (addrResolved != null) {
            log.debug("Resolved " + addr.getHostString() + " to " + addrResolved.getHostAddress());
            return new InetSocketAddress(addrResolved, addr.getPort());
        } else {
            // note: .onion nodes fall in here when proxy is Tor. But they have no IP address.
            // Unfortunately bitcoinj crashes in PeerAddress if it finds an unresolved address.
            log.error("Connected to " + addr.getHostString() + ".  But did not resolve to address.");
        }
    } catch (Exception e) {
        log.warn("Error resolving " + addr.getHostString() + ". Exception:\n" + e.toString());
    }
    return null;
}
 
Example 3
Source Project: dfactor   File: DFSocketManager.java    License: MIT License 6 votes vote down vote up
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
	_addrRemote = (InetSocketAddress) ctx.channel().remoteAddress();
	_session = new DFTcpChannelWrap(_addrRemote.getHostString(), _addrRemote.getPort(), 
			ctx.channel(), _decodeType, _encoder);
	_session.setOpenTime(System.currentTimeMillis());
	_sessionId = _session.getChannelId();
	//
	int actorId = 0;
	if(_dispatcher != null){
		actorId = _dispatcher.onConnActiveUnsafe(_requestId, _sessionId, _addrRemote);
	}else{  //没有notify指定
		actorId = _actorIdDef;
	}
	if(actorId != 0){ //actor有效
		_session.setStatusActor(actorId);
		_session.setMessageActor(actorId);
		//notify actor
		actorMgr.send(0, actorId, _requestId, 
				DFActorDefine.SUBJECT_NET, DFActorDefine.NET_TCP_CONNECT_OPEN, _session, true);
	}
	super.channelActive(ctx);
}
 
Example 4
private URI getProxyURI(HttpRequestImpl r) {
    InetSocketAddress proxy = r.proxy(exchange.client());
    if (proxy == null) {
        return null;
    }

    // our own private scheme for proxy URLs
    // eg. proxy.http://host:port/
    String scheme = "proxy." + r.uri().getScheme();
    try {
        return new URI(scheme,
                       null,
                       proxy.getHostString(),
                       proxy.getPort(),
                       null,
                       null,
                       null);
    } catch (URISyntaxException e) {
        throw new InternalError(e);
    }
}
 
Example 5
@Override
public InetSocketAddress proxyToServerResolutionStarted(String resolvingServerHostAndPort) {
    InetSocketAddress overrideAddress = null;
    String newServerHostAndPort = resolvingServerHostAndPort;

    for (HttpFilters filter : filters) {
        try {
            InetSocketAddress filterResult = filter.proxyToServerResolutionStarted(newServerHostAndPort);
            if (filterResult != null) {
                overrideAddress = filterResult;
                newServerHostAndPort = filterResult.getHostString() + ":" + filterResult.getPort();
            }
        } catch (RuntimeException e) {
            log.warn("Filter in filter chain threw exception. Filter method may have been aborted.", e);
        }
    }

    return overrideAddress;
}
 
Example 6
Source Project: netty-4.1.22   File: Socks5ProxyHandler.java    License: Apache License 2.0 6 votes vote down vote up
private void sendConnectCommand(ChannelHandlerContext ctx) throws Exception {
    InetSocketAddress raddr = destinationAddress();
    Socks5AddressType addrType;
    String rhost;
    if (raddr.isUnresolved()) {
        addrType = Socks5AddressType.DOMAIN;
        rhost = raddr.getHostString();
    } else {
        rhost = raddr.getAddress().getHostAddress();
        if (NetUtil.isValidIpV4Address(rhost)) {
            addrType = Socks5AddressType.IPv4;
        } else if (NetUtil.isValidIpV6Address(rhost)) {
            addrType = Socks5AddressType.IPv6;
        } else {
            throw new ProxyConnectException(
                    exceptionMessage("unknown address type: " + StringUtil.simpleClassName(rhost)));
        }
    }

    ctx.pipeline().replace(decoderName, decoderName, new Socks5CommandResponseDecoder());
    sendToProxyServer(new DefaultSocks5CommandRequest(Socks5CommandType.CONNECT, addrType, rhost, raddr.getPort()));
}
 
Example 7
Source Project: rpcx-java   File: NettyServer.java    License: Apache License 2.0 5 votes vote down vote up
public void start() {
    //默认的处理器
    this.defaultRequestProcessor = createDefaultRequestProcessor();
    //http网关请求处理器
    int httpProcessorNum = Integer.valueOf(Config.ins().get("rpcx.http.processor.num", "50"));
    this.registerProcessor(1984, new RpcHttpProcessor(this.getBeanFunc), new ThreadPoolExecutor(httpProcessorNum, httpProcessorNum,
            0L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<>(), new NamedThreadFactory("httpRequestProcessor")));


    ServerBootstrap childHandler = createServerBootstrap();
    try {
        String host = RemotingUtil.getLocalAddress();
        String port = getServerPort();
        ChannelFuture sync = this.serverBootstrap.bind(host, Integer.parseInt(port)).sync();
        InetSocketAddress addr = (InetSocketAddress) sync.channel().localAddress();
        logger.info("----->server bind finish");
        this.addr = addr.getHostString();
        this.port = addr.getPort();
        logger.info("###########rpc server start addr:{} ", this.addr + ":" + this.port);
    } catch (InterruptedException e1) {
        throw new RuntimeException("this.serverBootstrap.bind().sync() InterruptedException", e1);
    }

    if (this.channelEventListener != null) {
        new Thread(this.nettyEventExecuter).start();
    }

    runScanResponseTableSchedule();
    runProcessingRequestSchedule();
    addShutdownHook();
}
 
Example 8
Source Project: java-stratum   File: StratumClient.java    License: Apache License 2.0 5 votes vote down vote up
private void connectSocket() throws IOException {
    // TODO use random, exponentially backoff from failed connections
    InetSocketAddress address = serverAddresses.remove(0);
    serverAddresses.add(address);
    // Force resolution
    peerAddress = new InetSocketAddress(address.getHostString(), address.getPort());
    logger.info("Opening a socket to " + peerAddress.getHostString() + ":" + peerAddress.getPort());
    socket.connect(peerAddress); // TODO timeout
}
 
Example 9
Source Project: hadoop   File: TestWebHDFS.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testWebHdfsOffsetAndLength() throws Exception{
  MiniDFSCluster cluster = null;
  final Configuration conf = WebHdfsTestUtil.createConf();
  final int OFFSET = 42;
  final int LENGTH = 512;
  final String PATH = "/foo";
  byte[] CONTENTS = new byte[1024];
  RANDOM.nextBytes(CONTENTS);
  try {
    cluster = new MiniDFSCluster.Builder(conf).numDataNodes(1).build();
    final WebHdfsFileSystem fs =
        WebHdfsTestUtil.getWebHdfsFileSystem(conf, WebHdfsFileSystem.SCHEME);
    try (OutputStream os = fs.create(new Path(PATH))) {
      os.write(CONTENTS);
    }
    InetSocketAddress addr = cluster.getNameNode().getHttpAddress();
    URL url = new URL("http", addr.getHostString(), addr
        .getPort(), WebHdfsFileSystem.PATH_PREFIX + PATH + "?op=OPEN" +
        Param.toSortedString("&", new OffsetParam((long) OFFSET),
                             new LengthParam((long) LENGTH))
    );
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setInstanceFollowRedirects(true);
    Assert.assertEquals(LENGTH, conn.getContentLength());
    byte[] subContents = new byte[LENGTH];
    byte[] realContents = new byte[LENGTH];
    System.arraycopy(CONTENTS, OFFSET, subContents, 0, LENGTH);
    IOUtils.readFully(conn.getInputStream(), realContents);
    Assert.assertArrayEquals(subContents, realContents);
  } finally {
    if (cluster != null) {
      cluster.shutdown();
    }
  }
}
 
Example 10
private Address getAddress(PinpointServer pinpointServer) {
    final SocketAddress remoteAddress = pinpointServer.getRemoteAddress();
    if (!(remoteAddress instanceof InetSocketAddress)) {
        throw new IllegalStateException("unexpected address type:" + remoteAddress);
    }
    InetSocketAddress inetSocketAddress = (InetSocketAddress) remoteAddress;
    return new DefaultAddress(inetSocketAddress.getHostString(), inetSocketAddress.getPort());
}
 
Example 11
@Override
public void decode() {
    super.decode();
    this.offset += 16; //skip magic bytes
    InetSocketAddress address = this.getAddress();
    this.serverAddress = address.getHostString();
    this.serverPort = address.getPort();
    this.mtuSize = this.getSignedShort();
    this.clientID = this.getLong();
}
 
Example 12
@Override
public String getRemoteHost() {
    if (host == null) {
        InetSocketAddress addr = (InetSocketAddress) channel.remoteAddress();
        host = addr.getHostString();
    }
    return host;
}
 
Example 13
Source Project: Slyther   File: GameReplayer.java    License: MIT License 5 votes vote down vote up
public URI getURI() {
    try {
        InetSocketAddress addr = server.getAddress();
        return new URI("ws://" + addr.getHostString() + ":" + addr.getPort());
    } catch (URISyntaxException e) {
        throw new RuntimeException(e);
    }
}
 
Example 14
@Override
public void decode() {
    super.decode();
    InetSocketAddress addr = this.getAddress();
    this.address = addr.getHostString();
    this.port = addr.getPort();

    for (int i = 0; i < 10; i++) {
        this.systemAddresses[i] = this.getAddress();
    }

    this.sendPing = this.getLong();
    this.sendPong = this.getLong();
}
 
Example 15
public static String getSocketConnectString(InetSocketAddress socketAddress)
{
  String host;
  InetAddress address = socketAddress.getAddress();
  if (address == null) {
    host = socketAddress.getHostString();
  } else if (address.isAnyLocalAddress() || address.isLoopbackAddress()) {
    host = address.getCanonicalHostName();
  } else {
    host = address.getHostName();
  }
  return host + ":" + socketAddress.getPort();
}
 
Example 16
Source Project: docker-plugin   File: PortUtils.java    License: MIT License 4 votes vote down vote up
public static ConnectionCheck connectionCheck(InetSocketAddress address) {
    return new ConnectionCheck(address.getHostString(), address.getPort());
}
 
Example 17
private String getKey(InetSocketAddress address) {
    InetAddress addr = address.getAddress();
    return (addr == null ? address.getHostString() : addr.getHostAddress()) + ":" + address
            .getPort();
}
 
Example 18
/** 
 * @see com.talent.aio.common.ChannelContext#createClientNode(java.nio.channels.AsynchronousSocketChannel)
 * 
 * @param asynchronousSocketChannel
 * @return
 * @throws IOException 
 * @重写人: tanyaowu
 * @重写时间: 2016年12月6日 下午12:18:08
 * 
 */
@Override
public Node createClientNode(AsynchronousSocketChannel asynchronousSocketChannel) throws IOException
{
	InetSocketAddress inetSocketAddress = (InetSocketAddress) asynchronousSocketChannel.getRemoteAddress();
	Node clientNode = new Node(inetSocketAddress.getHostString(), inetSocketAddress.getPort());
	return clientNode;
}
 
Example 19
Source Project: flink   File: NetUtils.java    License: Apache License 2.0 3 votes vote down vote up
/**
 * Encodes an IP address and port to be included in URL. in particular, this method makes
 * sure that IPv6 addresses have the proper formatting to be included in URLs.
 *
 * @param address The socket address with the IP address and port.
 * @return The proper URL string encoded IP address and port.
 */
public static String socketAddressToUrlString(InetSocketAddress address) {
	if (address.isUnresolved()) {
		throw new IllegalArgumentException("Address cannot be resolved: " + address.getHostString());
	}
	return ipAddressAndPortToUrlString(address.getAddress(), address.getPort());
}
 
Example 20
Source Project: Flink-CEPplus   File: NetUtils.java    License: Apache License 2.0 3 votes vote down vote up
/**
 * Encodes an IP address and port to be included in URL. in particular, this method makes
 * sure that IPv6 addresses have the proper formatting to be included in URLs.
 *
 * @param address The socket address with the IP address and port.
 * @return The proper URL string encoded IP address and port.
 */
public static String socketAddressToUrlString(InetSocketAddress address) {
	if (address.isUnresolved()) {
		throw new IllegalArgumentException("Address cannot be resolved: " + address.getHostString());
	}
	return ipAddressAndPortToUrlString(address.getAddress(), address.getPort());
}