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

The following examples show how to use java.net.InetSocketAddress#getAddress() . 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: SctpMultiChannelImpl.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private int sendFromNativeBuffer(int fd,
                                 ByteBuffer bb,
                                 SocketAddress target,
                                 int assocId,
                                 int streamNumber,
                                 boolean unordered,
                                 int ppid)
        throws IOException {
    InetAddress addr = null;     // no preferred address
    int port = 0;
    if (target != null) {
        InetSocketAddress isa = Net.checkAddress(target);
        addr = isa.getAddress();
        port = isa.getPort();
    }
    int pos = bb.position();
    int lim = bb.limit();
    assert (pos <= lim);
    int rem = (pos <= lim ? lim - pos : 0);

    int written = send0(fd, ((DirectBuffer)bb).address() + pos, rem, addr,
                        port, assocId, streamNumber, unordered, ppid);
    if (written > 0)
        bb.position(pos + written);
    return written;
}
 
Example 2
Source File: SctpMultiChannelImpl.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
private int sendFromNativeBuffer(int fd,
                                 ByteBuffer bb,
                                 SocketAddress target,
                                 int assocId,
                                 int streamNumber,
                                 boolean unordered,
                                 int ppid)
        throws IOException {
    InetAddress addr = null;     // no preferred address
    int port = 0;
    if (target != null) {
        InetSocketAddress isa = Net.checkAddress(target);
        addr = isa.getAddress();
        port = isa.getPort();
    }
    int pos = bb.position();
    int lim = bb.limit();
    assert (pos <= lim);
    int rem = (pos <= lim ? lim - pos : 0);

    int written = send0(fd, ((DirectBuffer)bb).address() + pos, rem, addr,
                        port, assocId, streamNumber, unordered, ppid);
    if (written > 0)
        bb.position(pos + written);
    return written;
}
 
Example 3
Source File: TcpSocketModule.java    From react-native-tcp-socket with MIT License 6 votes vote down vote up
@Override
public void onConnection(Integer serverId, Integer clientId, InetSocketAddress socketAddress) {
    WritableMap eventParams = Arguments.createMap();
    eventParams.putInt("id", serverId);

    WritableMap infoParams = Arguments.createMap();
    infoParams.putInt("id", clientId);

    final InetAddress address = socketAddress.getAddress();

    WritableMap addressParams = Arguments.createMap();
    addressParams.putString("address", address.getHostAddress());
    addressParams.putInt("port", socketAddress.getPort());
    addressParams.putString("family", address instanceof Inet6Address ? "IPv6" : "IPv4");

    infoParams.putMap("address", addressParams);
    eventParams.putMap("info", infoParams);

    sendEvent("connection", eventParams);
}
 
Example 4
Source File: RpcContext.java    From rpcx-java with Apache License 2.0 6 votes vote down vote up
/**
 * is consumer side.
 *
 * @return consumer side.
 */
public boolean isConsumerSide() {
    URL url = getUrl();
    if (url == null) {
        return false;
    }
    InetSocketAddress address = getRemoteAddress();
    if (address == null) {
        return false;
    }
    String host;
    if (address.getAddress() == null) {
        host = address.getHostName();
    } else {
        host = address.getAddress().getHostAddress();
    }
    return url.getPort() == address.getPort() &&
            NetUtils.filterLocalHost(url.getIp()).equals(NetUtils.filterLocalHost(host));
}
 
Example 5
Source File: NetworkInterfaceAwareSocketFactory.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Socket createSocket() {
    return new HttpProxyAwareSocket(proxy) {
        @Override
        public void connect(final SocketAddress endpoint, final int timeout) throws IOException {
            if(endpoint instanceof InetSocketAddress) {
                final InetSocketAddress address = (InetSocketAddress) endpoint;
                if(address.getAddress() instanceof Inet6Address) {
                    final NetworkInterface network = findIPv6Interface((Inet6Address) address.getAddress());
                    if(null != network) {
                        super.connect(new InetSocketAddress(
                            NetworkInterfaceAwareSocketFactory.this.getByAddressForInterface(network, address.getAddress()),
                            address.getPort()), timeout);
                        return;
                    }
                }
            }
            super.connect(endpoint, timeout);
        }
    };
}
 
Example 6
Source File: Net.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
static InetSocketAddress checkAddress(SocketAddress sa, ProtocolFamily family) {
    InetSocketAddress isa = checkAddress(sa);
    if (family == StandardProtocolFamily.INET) {
        InetAddress addr = isa.getAddress();
        if (!(addr instanceof Inet4Address))
            throw new UnsupportedAddressTypeException();
    }
    return isa;
}
 
Example 7
Source File: RemoteIPAttribute.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public String readAttribute(final HttpServerExchange exchange) {
    final InetSocketAddress sourceAddress = exchange.getSourceAddress();
    InetAddress address = sourceAddress.getAddress();
    if (address == null) {
        //this can happen when we have an unresolved X-forwarded-for address
        //in this case we just return the IP of the balancer
        address = ((InetSocketAddress) exchange.getConnection().getPeerAddress()).getAddress();
    }
    if(address == null) {
        return null;
    }
    return address.getHostAddress();
}
 
Example 8
Source File: HttpAsyncDownloaderBuilder.java    From JMCCC with MIT License 5 votes vote down vote up
private static HttpHost resolveProxy(Proxy proxy) {
	if (proxy.type() == Proxy.Type.DIRECT) {
		return null;
	}
	if (proxy.type() == Proxy.Type.HTTP) {
		SocketAddress socketAddress = proxy.address();
		if (socketAddress instanceof InetSocketAddress) {
			InetSocketAddress inetSocketAddress = (InetSocketAddress) socketAddress;
			return new HttpHost(inetSocketAddress.getAddress(), inetSocketAddress.getPort());
		}
	}
	throw new IllegalArgumentException("Proxy '" + proxy + "' is not supported");
}
 
Example 9
Source File: DetailCapture.java    From glowroot with Apache License 2.0 5 votes vote down vote up
private static @Nullable String getRemoteAddr(@Nullable InetSocketAddress remoteAddress) {
    if (remoteAddress != null && remoteAddress.getAddress() != null) {
        return remoteAddress.getAddress().getHostAddress();
    } else {
        return null;
    }
}
 
Example 10
Source File: Packet.java    From JRakNet with MIT License 5 votes vote down vote up
/**
 * Writes an IPv4/IPv6 address to the packet.
 * 
 * @param address
 *            the address.
 * @return the packet.
 * @throws NullPointerException
 *             if the <code>address</code> or IP address are
 *             <code>null</code>.
 * @throws UnknownHostException
 *             if no IP address for the <code>host</code> could be found, if
 *             a <code>scope_id</code> was specified for a global IPv6
 *             address, or the length of the address is not either
 *             {@value RakNet#IPV4_ADDRESS_LENGTH} or
 *             {@value RakNet#IPV6_ADDRESS_LENGTH} <code>byte</code>s.
 */
public final Packet writeAddress(InetSocketAddress address) throws NullPointerException, UnknownHostException {
	if (address == null) {
		throw new NullPointerException("Address cannot be null");
	} else if (address.getAddress() == null) {
		throw new NullPointerException("IP address cannot be null");
	}
	byte[] ipAddress = address.getAddress().getAddress();
	int version = RakNet.getAddressVersion(address);
	if (version == RakNet.IPV4) {
		this.writeUnsignedByte(RakNet.IPV4);
		for (int i = 0; i < ipAddress.length; i++) {
			this.writeByte(~ipAddress[i] & 0xFF);
		}
		this.writeUnsignedShort(address.getPort());
	} else if (version == RakNet.IPV6) {
		this.writeUnsignedByte(RakNet.IPV6);
		this.writeShortLE(RakNet.AF_INET6);
		this.writeShort(address.getPort());
		this.writeInt(0x00); // Flow info
		this.write(ipAddress);
		this.writeInt(0x00); // Scope ID
	} else {
		throw new UnknownHostException(
				"Unknown protocol for address with length of " + ipAddress.length + " bytes");
	}
	return this;
}
 
Example 11
Source File: IPAddressUtil.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
/**
 * Same as above for InetSocketAddress
 */
public static InetSocketAddress toScopedAddress(InetSocketAddress address)
    throws SocketException {
    InetAddress addr;
    InetAddress orig = address.getAddress();
    if ((addr = toScopedAddress(orig)) == orig) {
        return address;
    } else {
        return new InetSocketAddress(addr, address.getPort());
    }
}
 
Example 12
Source File: Node.java    From xmrwallet with Apache License 2.0 5 votes vote down vote up
public Node(InetSocketAddress socketAddress) {
    this();
    this.hostAddress = socketAddress.getAddress();
    this.host = socketAddress.getHostString();
    this.rpcPort = 0; // unknown
    this.levinPort = socketAddress.getPort();
    this.username = "";
    this.password = "";
    //this.name = socketAddress.getHostName(); // triggers DNS so we don't do it by default
}
 
Example 13
Source File: HttpServletRequestAdapter.java    From cxf with Apache License 2.0 5 votes vote down vote up
public String getRemoteAddr() {
    InetSocketAddress isa = exchange.getRemoteAddress();
    if (isa != null) {
        InetAddress ia = isa.getAddress();
        if (ia != null) {
            return ia.getHostAddress();
        }
    }
    return null;
}
 
Example 14
Source File: ExtendedConnectionOperator.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
private boolean addressTypesMatch(InetSocketAddress localSocketAddress, InetAddress remoteAddress) {
  InetAddress localAddress = localSocketAddress != null ? localSocketAddress.getAddress() : null;

  if (localAddress == null || remoteAddress == null) {
    return true;
  }

  return (localAddress instanceof Inet4Address && remoteAddress instanceof Inet4Address) ||
      (localAddress instanceof Inet6Address && remoteAddress instanceof Inet6Address);
}
 
Example 15
Source File: ServerPeer.java    From dubbox with Apache License 2.0 5 votes vote down vote up
@Override
public Channel getChannel(InetSocketAddress remoteAddress) {
    String host = remoteAddress.getAddress() != null ? remoteAddress.getAddress().getHostAddress() : remoteAddress.getHostName();
    int port = remoteAddress.getPort();
    Channel channel = super.getChannel(remoteAddress);
    if (channel == null) {
        for (Map.Entry<URL, Client> entry : clients.entrySet()) {
            URL url = entry.getKey();
            if (url.getIp().equals(host) && url.getPort() == port) {
                return entry.getValue();
            }
        }
    }
    return channel;
}
 
Example 16
Source File: AddressUtils.java    From bt with Apache License 2.0 4 votes vote down vote up
public static String toString(InetSocketAddress sockAddr) {
	InetAddress addr = sockAddr.getAddress();
	if(addr instanceof Inet6Address)
		return String.format("%41s:%-5d", "[" + addr.getHostAddress() + "]", sockAddr.getPort());
	return String.format("%15s:%-5d", addr.getHostAddress(), sockAddr.getPort());
}
 
Example 17
Source File: AbstractLoginListener.java    From ProtocolSupport with GNU Affero General Public License v3.0 4 votes vote down vote up
protected void finishLogin() throws InterruptedException, ExecutionException  {
	if (!networkManager.isConnected()) {
		return;
	}

	cancelTimeoutTask();

	LoginProfile profile = connection.getLoginProfile();
	InetSocketAddress saddress = networkManager.getAddress();

	InetAddress address = saddress.getAddress();

	PlayerProfileCompleteEvent event = new PlayerProfileCompleteEvent(connection);
	Bukkit.getPluginManager().callEvent(event);
	if (event.isLoginDenied()) {
		disconnect(event.getDenyLoginMessage());
		return;
	}
	if (event.getForcedName() != null) {
		profile.setName(event.getForcedName());
	}
	if (event.getForcedUUID() != null) {
		profile.setUUID(event.getForcedUUID());
	}
	event.getProperties().values().forEach(c -> c.forEach(profile::addProperty));

	AsyncPlayerPreLoginEvent asyncEvent = new AsyncPlayerPreLoginEvent(profile.getName(), address, profile.getUUID());
	Bukkit.getPluginManager().callEvent(asyncEvent);

	PlayerPreLoginEvent syncEvent = new PlayerPreLoginEvent(profile.getName(), address, profile.getUUID());
	if (asyncEvent.getResult() != PlayerPreLoginEvent.Result.ALLOWED) {
		syncEvent.disallow(asyncEvent.getResult(), asyncEvent.getKickMessage());
	}
	if (PlayerPreLoginEvent.getHandlerList().getRegisteredListeners().length != 0) {
		if (ServerPlatform.get().getMiscUtils().callSyncTask(() -> {
			Bukkit.getPluginManager().callEvent(syncEvent);
			return syncEvent.getResult();
		}).get() != PlayerPreLoginEvent.Result.ALLOWED) {
			disconnect(syncEvent.getKickMessage());
			return;
		}
	}

	if (syncEvent.getResult() != PlayerPreLoginEvent.Result.ALLOWED) {
		disconnect(syncEvent.getKickMessage());
		return;
	}

	Bukkit.getLogger().info("UUID of player " + connection.getProfile().getName() + " is " + connection.getProfile().getUUID());

	if (hasCompression(connection.getVersion())) {
		int threshold = ServerPlatform.get().getMiscUtils().getCompressionThreshold();
		if (threshold >= 0) {
			CountDownLatch waitpacketsend = new CountDownLatch(1);
			connection.submitIOTask(() -> networkManager.sendPacket(
				ServerPlatform.get().getPacketFactory().createSetCompressionPacket(threshold),
				future -> {
					ServerPlatform.get().getMiscUtils().enableCompression(networkManager.getChannel().pipeline(), threshold);
					waitpacketsend.countDown();
				}
			));
			try {
				if (!waitpacketsend.await(5, TimeUnit.SECONDS)) {
					disconnect("Timeout while waiting for login success send");
					return;
				}
			} catch (InterruptedException e) {
				disconnect("Exception while waiting for login success send");
				return;
			}
		}
	}

	AbstractLoginListenerPlay listener = getLoginListenerPlay();
	networkManager.setPacketListener(listener);
	listener.finishLogin();
}
 
Example 18
Source File: EndpointIntegrationTest.java    From simulacron with Apache License 2.0 4 votes vote down vote up
@Test
public void testDeleteParticularConnection() throws Exception {
  Collection<BoundDataCenter> datacenters = server.getCluster().getDataCenters();
  BoundDataCenter dc = datacenters.iterator().next();
  Iterator<BoundNode> nodeIterator = dc.getNodes().iterator();
  BoundNode node = nodeIterator.next();

  try (com.datastax.driver.core.Cluster driverCluster =
      defaultBuilder().addContactPointsWithPorts((InetSocketAddress) node.getAddress()).build()) {
    driverCluster.init();

    assertThat(driverCluster.getMetadata().getAllHosts()).hasSize(6);
    driverCluster.connect();

    Scope scope = new Scope(server.getCluster().getId(), dc.getId(), node.getId());
    HttpTestResponse response = server.get("/connections/" + scope.toString());

    ClusterConnectionReport clusterReport =
        om.readValue(response.body, ClusterConnectionReport.class);
    NodeConnectionReport connectionNode =
        clusterReport
            .getDataCenters()
            .stream()
            .filter(dce -> dce.getId().equals(dc.getId()))
            .flatMap(d -> d.getNodes().stream())
            .filter(n -> n.getId().equals(node.getId()))
            .findAny()
            .get();
    InetSocketAddress connection = (InetSocketAddress) connectionNode.getConnections().get(0);

    HttpTestResponse deleteResponse =
        server.delete(
            "/connection/"
                + server.getCluster().getId()
                + connection.getAddress()
                + "/"
                + connection.getPort());
    assertThat(deleteResponse.response.statusCode()).isEqualTo(200);

    HttpTestResponse responseAfter = server.get("/connections/" + scope.toString());

    String sAString = connection.getAddress() + ":" + connection.getPort();
    String sAtrimmed = sAString.substring(1, sAString.length());
    assertThat(responseAfter.body).isNotEqualTo(response.body);
    assertThat(responseAfter.body).doesNotContain(sAtrimmed);
    assertThat(deleteResponse.body).contains(sAtrimmed);
  }
}
 
Example 19
Source File: TestUtil.java    From mycore with GNU General Public License v3.0 4 votes vote down vote up
public static InetAddress getLocalAdress(String remoteHost, int port) throws IOException {
    InetSocketAddress socketAddr = new InetSocketAddress(remoteHost, port);
    SocketChannel socketChannel = SocketChannel.open(socketAddr);
    InetSocketAddress localAddress = (InetSocketAddress) socketChannel.getLocalAddress();
    return localAddress.getAddress();
}
 
Example 20
Source File: ConnectionUtils.java    From flink with Apache License 2.0 4 votes vote down vote up
/**
 * Try to find a local address which allows as to connect to the targetAddress using the given
 * strategy.
 *
 * @param strategy Depending on the strategy, the method will enumerate all interfaces, trying to connect
 *                 to the target address
 * @param targetAddress The address we try to connect to
 * @param logging Boolean indicating the logging verbosity
 * @return null if we could not find an address using this strategy, otherwise, the local address.
 * @throws IOException
 */
private static InetAddress findAddressUsingStrategy(AddressDetectionState strategy,
													InetSocketAddress targetAddress,
													boolean logging) throws IOException {
	// try LOCAL_HOST strategy independent of the network interfaces
	if (strategy == AddressDetectionState.LOCAL_HOST) {
		InetAddress localhostName;
		try {
			localhostName = InetAddress.getLocalHost();
		} catch (UnknownHostException uhe) {
			LOG.warn("Could not resolve local hostname to an IP address: {}", uhe.getMessage());
			return null;
		}

		if (tryToConnect(localhostName, targetAddress, strategy.getTimeout(), logging)) {
			LOG.debug("Using InetAddress.getLocalHost() immediately for the connecting address");
			// Here, we are not calling tryLocalHostBeforeReturning() because it is the LOCAL_HOST strategy
			return localhostName;
		} else {
			return null;
		}
	}

	final InetAddress address = targetAddress.getAddress();
	if (address == null) {
		return null;
	}
	final byte[] targetAddressBytes = address.getAddress();

	// for each network interface
	Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces();
	while (e.hasMoreElements()) {

		NetworkInterface netInterface = e.nextElement();

		// for each address of the network interface
		Enumeration<InetAddress> ee = netInterface.getInetAddresses();
		while (ee.hasMoreElements()) {
			InetAddress interfaceAddress = ee.nextElement();

			switch (strategy) {
				case ADDRESS:
					if (hasCommonPrefix(targetAddressBytes, interfaceAddress.getAddress())) {
						LOG.debug("Target address {} and local address {} share prefix - trying to connect.",
									targetAddress, interfaceAddress);

						if (tryToConnect(interfaceAddress, targetAddress, strategy.getTimeout(), logging)) {
							return tryLocalHostBeforeReturning(interfaceAddress, targetAddress, logging);
						}
					}
					break;

				case FAST_CONNECT:
				case SLOW_CONNECT:
					LOG.debug("Trying to connect to {} from local address {} with timeout {}",
							targetAddress, interfaceAddress, strategy.getTimeout());

					if (tryToConnect(interfaceAddress, targetAddress, strategy.getTimeout(), logging)) {
						return tryLocalHostBeforeReturning(interfaceAddress, targetAddress, logging);
					}
					break;

				case HEURISTIC:
					if (LOG.isDebugEnabled()) {
						LOG.debug("Choosing InetAddress.getLocalHost() address as a heuristic.");
					}

					return InetAddress.getLocalHost();

				default:
					throw new RuntimeException("Unsupported strategy: " + strategy);
			}
		} // end for each address of the interface
	} // end for each interface

	return null;
}