Java Code Examples for java.net.SocketAddress#toString()

The following examples show how to use java.net.SocketAddress#toString() . 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: RemotingHelper.java    From DDMQ with Apache License 2.0 6 votes vote down vote up
public static String parseChannelRemoteAddr(final Channel channel) {
    if (null == channel) {
        return "";
    }
    SocketAddress remote = channel.remoteAddress();
    final String addr = remote != null ? remote.toString() : "";

    if (addr.length() > 0) {
        int index = addr.lastIndexOf("/");
        if (index >= 0) {
            return addr.substring(index + 1);
        }

        return addr;
    }

    return "";
}
 
Example 2
Source File: IpUtil.java    From journalkeeper with Apache License 2.0 6 votes vote down vote up
/**
 * 把地址对象转换成字符串
 *
 * @param address 地址
 * @return 地址字符串
 */
public static String toAddress(final SocketAddress address) {
    if (address == null) {
        return null;
    }
    if (address instanceof InetSocketAddress && !((InetSocketAddress) address).isUnresolved()) {
        InetSocketAddress isa = (InetSocketAddress) address;

        StringBuilder builder = new StringBuilder(50);
        builder.append(isa.getAddress().getHostAddress());
        String separator = isValidIpV4Address(isa.getAddress().getHostAddress()) ? IPV4_PORT_SEPARATOR : IPV6_PORT_SEPARATOR;
        builder.append(separator).append(isa.getPort());
        return builder.toString();
    } else {
        return address.toString();
    }
}
 
Example 3
Source File: ChannelTrafficStatisticsHandler.java    From x-pipe with Apache License 2.0 6 votes vote down vote up
protected void parseIpPort(final Channel channel) {
    if (null == channel) {
        return;
    }
    final SocketAddress remote = channel.remoteAddress();
    final String addr = remote != null ? remote.toString() : "";

    if (addr.length() > 0) {
        int index = addr.lastIndexOf("/");
        if (index >= 0) {
            String ipPort = addr.substring(index + 1);
            String[] splits = ipPort.split(":");
            if (splits != null && splits.length == 2) {
                ip = splits[0];
                try {
                    port = Integer.parseInt(splits[1]);
                } catch (NumberFormatException e) {
                    // ignore
                }
            }
        }

    }
}
 
Example 4
Source File: NettyUtil.java    From DistributedID with Apache License 2.0 6 votes vote down vote up
/**
 * 获取Channel的远程IP地址
 * @param channel
 * @return
 */
public static String parseRemoteAddr(final Channel channel) {
    if (null == channel) {
        return "";
    }
    SocketAddress remote = channel.remoteAddress();
    final String addr = remote != null ? remote.toString() : "";

    if (addr.length() > 0) {
        int index = addr.lastIndexOf("/");
        if (index >= 0) {
            return addr.substring(index + 1);
        }

        return addr;
    }

    return "";
}
 
Example 5
Source File: MemcachedMonitor.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
/**
 * Get cache statistics for all memcached hosts known to {@link MemcachedClientIF}.
 *
 * @return Statistics for all available hosts.
 */
protected CacheStatistics[] getStatistics() {
    long evictions;
    long size;
    long capacity;
    String name;
    Map<String, String> statsMap;
    final Map<SocketAddress, Map<String, String>> allStats = memcachedClient.getStats();
    final List<CacheStatistics> statsList = new ArrayList<CacheStatistics>();
    for (final SocketAddress address : allStats.keySet()) {
        statsMap = allStats.get(address);
        if (statsMap.size() > 0) {
            size = Long.parseLong(statsMap.get("bytes"));
            capacity = Long.parseLong(statsMap.get("limit_maxbytes"));
            evictions = Long.parseLong(statsMap.get("evictions"));
            if (address instanceof InetSocketAddress) {
                name = ((InetSocketAddress) address).getHostName();
            } else {
                name = address.toString();
            }
            statsList.add(new SimpleCacheStatistics(size, capacity, evictions, name));
        }
    }
    return statsList.toArray(new CacheStatistics[statsList.size()]);
}
 
Example 6
Source File: AbstractMqttChannel.java    From xenqtt with Apache License 2.0 6 votes vote down vote up
/**
 * @see net.xenqtt.message.MqttChannel#getLocalAddress()
 */
@Override
public String getLocalAddress() {

	if (localAddress == null) {
		Socket socket = channel.socket();
		if (!channel.isOpen()) {
			return "N/A";
		}

		SocketAddress address = socket.getLocalSocketAddress();
		if (address == null) {
			return "N/A";
		}
		localAddress = address.toString();
	}

	return localAddress;
}
 
Example 7
Source File: RemotingHelper.java    From rocketmq-4.3.0 with Apache License 2.0 6 votes vote down vote up
public static String parseChannelRemoteAddr(final Channel channel) {
    if (null == channel) {
        return "";
    }
    SocketAddress remote = channel.remoteAddress();
    final String addr = remote != null ? remote.toString() : "";

    if (addr.length() > 0) {
        int index = addr.lastIndexOf("/");
        if (index >= 0) {
            return addr.substring(index + 1);
        }

        return addr;
    }

    return "";
}
 
Example 8
Source File: NettyUtil.java    From iot-mqtt with Apache License 2.0 6 votes vote down vote up
public static String getRemoteAddr(Channel channel){
    if (null == channel) {
        return "";
    }
    SocketAddress remote = channel.remoteAddress();
    final String addr = remote != null ? remote.toString() : "";
    if (addr.length() > 0) {
        int index = addr.lastIndexOf("/");
        if (index >= 0) {
            return addr.substring(index + 1);
        }

        return addr;
    }
    return "";
}
 
Example 9
Source File: IMAPMDCContext.java    From james-project with Apache License 2.0 5 votes vote down vote up
private static String retrieveIp(ChannelHandlerContext ctx) {
    SocketAddress remoteAddress = ctx.getChannel().getRemoteAddress();
    if (remoteAddress instanceof InetSocketAddress) {
        InetSocketAddress address = (InetSocketAddress) remoteAddress;
        return address.getAddress().getHostAddress();
    }
    return remoteAddress.toString();
}
 
Example 10
Source File: SocketChannelWithTimeouts.java    From jmeter-plugins with Apache License 2.0 5 votes vote down vote up
@Override
public boolean connect(SocketAddress remote) throws IOException {

    long start = System.currentTimeMillis();
    //log.debug("trying to connect");
    socketChannel.connect(remote);
    if (selector.select(connectTimeout) > 0) {
        selector.selectedKeys().remove(channelKey);
        //log.debug("selected connect");
        //log.debug("Spent " + (System.currentTimeMillis() - start));
        if (!channelKey.isConnectable()) {
            throw new IllegalStateException("Socket channel is in not connectable state");
        }

        socketChannel.finishConnect();
        channelKey = socketChannel.register(selector, SelectionKey.OP_READ);
        if (log.isDebugEnabled()) {
            log.debug("Connected socket in " + (System.currentTimeMillis() - start));
        }
        if (!socketChannel.isConnected()) {
            throw new SocketException("SocketChannel not connected on some reason");
        }
        return true;
    }
    //log.debug("Spent " + (System.currentTimeMillis() - start));
    throw new SocketTimeoutException("Failed to connect to " + remote.toString());
}
 
Example 11
Source File: RemotingHelper.java    From elephant with Apache License 2.0 5 votes vote down vote up
public static String parseSocketAddressAddr(SocketAddress socketAddress) {
    if (socketAddress != null) {
        final String addr = socketAddress.toString();

        if (addr.length() > 0) {
            return addr.substring(1);
        }
    }
    return "";
}
 
Example 12
Source File: NettyBootStrapper.java    From ovsdb with Eclipse Public License 1.0 5 votes vote down vote up
public int getServerPort() {
    SocketAddress socketAddress = channelFuture.channel().localAddress();
    if (socketAddress instanceof InetSocketAddress) {
        InetSocketAddress inetSocketAddress = (InetSocketAddress) socketAddress;
        return inetSocketAddress.getPort();
    } else {
        throw new NotImplementedException("Please implement how to obtain port from a " + socketAddress.toString());
    }
}
 
Example 13
Source File: ChannelOption.java    From lippen-network-tool with Apache License 2.0 5 votes vote down vote up
@Override
public String toString() {
    SocketAddress address = channel.remoteAddress();
    address = address == null ? channel.localAddress() : address;
    if (address instanceof InetSocketAddress) {
        InetSocketAddress add = (InetSocketAddress) address;
        return add.getHostString() + ":" + add.getPort();
    }
    return address.toString();
}
 
Example 14
Source File: RemotingHelper.java    From DDMQ with Apache License 2.0 5 votes vote down vote up
public static String parseSocketAddressAddr(SocketAddress socketAddress) {
    if (socketAddress != null) {
        final String addr = socketAddress.toString();

        if (addr.length() > 0) {
            return addr.substring(1);
        }
    }
    return "";
}
 
Example 15
Source File: RemotingUtil.java    From eagle with Apache License 2.0 5 votes vote down vote up
public static String parseChannelRemoteAddr(final Channel channel) {
    if (null == channel) {
        return "";
    }
    SocketAddress remote = channel.remoteAddress();
    final String addr = remote != null ? remote.toString() : "";
    if (addr.length() > 0) {
        int index = addr.lastIndexOf("/");
        if (index >= 0) {
            return addr.substring(index + 1);
        }
        return addr;
    }
    return "";
}
 
Example 16
Source File: PerServerConnectionPool.java    From zuul with Apache License 2.0 5 votes vote down vote up
private static String getSelectedHostString(SocketAddress addr) {
    if (addr instanceof InetSocketAddress) {
        // This is used for logging mainly.  TODO(carl-mastrangelo): consider passing the whole address back
        // rather than the string form.
        return ((InetSocketAddress) addr).getAddress().getHostAddress();
    } else {
        // If it's some other kind of address, just set it to the string form as a best effort guess.
        return addr.toString();
    }
}
 
Example 17
Source File: IMAPMDCContext.java    From james-project with Apache License 2.0 5 votes vote down vote up
private static String retrieveHost(ChannelHandlerContext ctx) {
    SocketAddress remoteAddress = ctx.getChannel().getRemoteAddress();
    if (remoteAddress instanceof InetSocketAddress) {
        InetSocketAddress address = (InetSocketAddress) remoteAddress;
        return address.getHostName();
    }
    return remoteAddress.toString();
}
 
Example 18
Source File: AuthenticationResultCacher.java    From qpid-broker-j with Apache License 2.0 4 votes vote down vote up
private String digestCredentials(final String... content)
{
    try
    {
        MessageDigest md = MessageDigest.getInstance("SHA-256");

        Subject subject = Subject.getSubject(AccessController.getContext());
        Set<SocketConnectionPrincipal> connectionPrincipals = subject.getPrincipals(SocketConnectionPrincipal.class);
        if (connectionPrincipals != null && !connectionPrincipals.isEmpty())
        {
            SocketConnectionPrincipal connectionPrincipal = connectionPrincipals.iterator().next();
            SocketAddress remoteAddress = connectionPrincipal.getRemoteAddress();
            String address;
            if (remoteAddress instanceof InetSocketAddress)
            {
                address = ((InetSocketAddress) remoteAddress).getHostString();
            }
            else
            {
                address = remoteAddress.toString();
            }
            if (address != null)
            {
                md.update(address.getBytes(UTF8));
            }
        }

        for (String part : content)
        {
            md.update(part.getBytes(UTF8));
        }

        byte[] credentialDigest = md.digest();
        for (int i = 0; i < _iterationCount; ++i)
        {
            md = MessageDigest.getInstance("SHA-256");
            credentialDigest = md.digest(credentialDigest);
        }

        return StringUtil.toHex(credentialDigest);
    }
    catch (NoSuchAlgorithmException e)
    {
        throw new RuntimeException("JVM is non compliant. Seems to not support SHA-256.");
    }
}
 
Example 19
Source File: ClientPool.java    From incubator-retired-blur with Apache License 2.0 4 votes vote down vote up
private String getIdentifer(Socket socket) {
  SocketAddress localSocketAddress = socket.getLocalSocketAddress();
  SocketAddress remoteSocketAddress = socket.getRemoteSocketAddress();
  return localSocketAddress.toString() + " -> " + remoteSocketAddress.toString();
}
 
Example 20
Source File: EndpointIntegrationTest.java    From simulacron with Apache License 2.0 4 votes vote down vote up
@Test
public void testDeleteConnections() throws Exception {
  Collection<BoundDataCenter> datacenters = server.getCluster().getDataCenters();
  BoundDataCenter dc = datacenters.iterator().next();
  Iterator<BoundNode> nodeIterator = dc.getNodes().iterator();
  BoundNode node = nodeIterator.next();

  ArrayList<Scope> list = new ArrayList<>();
  list.add(new Scope(server.getCluster().getId(), dc.getId(), node.getId()));
  list.add(new Scope(server.getCluster().getId(), dc.getId(), null));
  list.add(new Scope(server.getCluster().getId(), null, null));

  for (Scope scope : list) {
    try (com.datastax.driver.core.Cluster driverCluster =
        defaultBuilder()
            .addContactPointsWithPorts((InetSocketAddress) node.getAddress())
            .build()) {
      driverCluster.init();
      HttpTestResponse responseDelete =
          server.delete("/connections/" + scope.toString() + "?type=disconnect");

      ClusterConnectionReport responseReport =
          om.readValue(responseDelete.body, ClusterConnectionReport.class);
      Collection<NodeConnectionReport> nodes =
          getNodeConnectionReports(responseReport, dc.getId());

      assertThat(responseDelete.response.statusCode()).isEqualTo(200);

      HttpTestResponse responseNewConnections = server.get("/connections/" + scope.toString());
      assertThat(responseNewConnections.body).isNotEqualTo(responseDelete.body);
      for (NodeConnectionReport nodeReport : nodes) {
        for (SocketAddress sA : nodeReport.getConnections()) {
          String sAString = sA.toString();
          assertThat(responseDelete.body).contains(sAString.substring(1, sAString.length()));
          assertThat(responseNewConnections.body)
              .doesNotContain(sAString.substring(1, sAString.length()));
        }
      }
    }
  }
}