List of usage examples for java.net InetAddress getByAddress
public static InetAddress getByAddress(byte[] addr) throws UnknownHostException
From source file:com.github.veqryn.net.Ip4.java
/** * This method uses InetAddress.getByAddress, and so does not block. * * @return java.net.InetAddress representing this IPv4 address * @throws UnknownHostException if not host found *//* w w w .j a v a2 s . c o m*/ public final InetAddress getInetAddress() throws UnknownHostException { final int[] ints = toArray(address, false); return InetAddress .getByAddress(new byte[] { (byte) ints[0], (byte) ints[1], (byte) ints[2], (byte) ints[3] }); }
From source file:com.predic8.membrane.integration.AccessControlInterceptorIntegrationTest.java
private HttpClient getClient(byte[] ip) throws UnknownHostException { HttpClient client = new HttpClient(); HostConfiguration config = new HostConfiguration(); config.setLocalAddress(InetAddress.getByAddress(ip)); client.setHostConfiguration(config); return client; }
From source file:org.geoserver.cluster.hazelcast.HzSynchronizerTest.java
protected static InetAddress localAddress(int i) throws Exception { return InetAddress.getByAddress(new byte[] { (byte) 192, (byte) 168, 0, (byte) i }); }
From source file:com.offbynull.portmapper.pcp.PeerPcpResponse.java
/** * Constructs a {@link PeerPcpResponse} object by parsing a buffer. * @param buffer buffer containing PCP response data * @throws NullPointerException if any argument is {@code null} * @throws BufferUnderflowException if not enough data is available in {@code buffer} * @throws IllegalArgumentException if there's not enough or too much data remaining in the buffer, or if the version doesn't match the * expected version (must always be {@code 2}), or if the r-flag isn't set, or if there's an unsuccessful/unrecognized result code, * or if the op code doesn't match the PEER opcode, or if the response has a {@code 0} for its {@code internalPort} or * {@code assignedExternalPort} or {@code remotePeerPort} or {@code protocol} field, or if there were problems parsing options *///ww w. j a v a2 s. c om public PeerPcpResponse(ByteBuffer buffer) { super(buffer); Validate.isTrue(super.getOp() == 2); mappingNonce = ByteBuffer.allocate(12); buffer.get(mappingNonce.array()); mappingNonce = mappingNonce.asReadOnlyBuffer(); this.protocol = buffer.get() & 0xFF; for (int i = 0; i < 3; i++) { // reserved block buffer.get(); } this.internalPort = buffer.getShort() & 0xFFFF; this.assignedExternalPort = buffer.getShort() & 0xFFFF; byte[] addrArr = new byte[16]; buffer.get(addrArr); try { this.assignedExternalIpAddress = InetAddress.getByAddress(addrArr); // should automatically shift down to ipv4 if ipv4-to-ipv6 // mapped address } catch (UnknownHostException uhe) { throw new IllegalArgumentException(uhe); // should never happen, will always be 16 bytes } this.remotePeerPort = buffer.getShort() & 0xFFFF; for (int i = 0; i < 2; i++) { // reserved block buffer.get(); } buffer.get(addrArr); try { this.remotePeerIpAddress = InetAddress.getByAddress(addrArr); // should automatically shift down to ipv4 if ipv4-to-ipv6 // mapped address } catch (UnknownHostException uhe) { throw new IllegalArgumentException(uhe); // should never happen, will always be 16 bytes } Validate.inclusiveBetween(1, 255, protocol); Validate.inclusiveBetween(1, 65535, internalPort); Validate.inclusiveBetween(1, 65535, assignedExternalPort); Validate.inclusiveBetween(1, 65535, remotePeerPort); parseOptions(buffer); }
From source file:com.ea.core.bridge.ws.rest.client.AbstractRestClient.java
public AbstractRestClient(URL httpUrl) { super(httpUrl); HttpMessageParserFactory<HttpResponse> responseParserFactory = new DefaultHttpResponseParserFactory() { @Override/*from w w w. j a va 2s. c om*/ public HttpMessageParser<HttpResponse> create(SessionInputBuffer buffer, MessageConstraints constraints) { LineParser lineParser = new BasicLineParser() { @Override public Header parseHeader(final CharArrayBuffer buffer) { try { return super.parseHeader(buffer); } catch (ParseException ex) { return new BasicHeader(buffer.toString(), null); } } }; return new DefaultHttpResponseParser(buffer, lineParser, DefaultHttpResponseFactory.INSTANCE, constraints) { @Override protected boolean reject(final CharArrayBuffer line, int count) { // try to ignore all garbage preceding a status line infinitely return false; } }; } }; HttpMessageWriterFactory<HttpRequest> requestWriterFactory = new DefaultHttpRequestWriterFactory(); HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> connFactory = new ManagedHttpClientConnectionFactory( requestWriterFactory, responseParserFactory); SSLContext sslcontext = SSLContexts.createSystemDefault(); X509HostnameVerifier hostnameVerifier = new BrowserCompatHostnameVerifier(); Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.INSTANCE) .register("https", new SSLConnectionSocketFactory(sslcontext, hostnameVerifier)).build(); DnsResolver dnsResolver = new SystemDefaultDnsResolver() { @Override public InetAddress[] resolve(final String host) throws UnknownHostException { if (host.equalsIgnoreCase("myhost") || host.equalsIgnoreCase("localhost")) { return new InetAddress[] { InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 }) }; } else { return super.resolve(host); } } }; PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager( socketFactoryRegistry, connFactory, dnsResolver); SocketConfig socketConfig = SocketConfig.custom().setTcpNoDelay(true).build(); connManager.setDefaultSocketConfig(socketConfig); connManager.setSocketConfig(new HttpHost("somehost", 80), socketConfig); MessageConstraints messageConstraints = MessageConstraints.custom().setMaxHeaderCount(200) .setMaxLineLength(2000).build(); ConnectionConfig connectionConfig = ConnectionConfig.custom() .setMalformedInputAction(CodingErrorAction.IGNORE) .setUnmappableInputAction(CodingErrorAction.IGNORE).setCharset(Consts.UTF_8) .setMessageConstraints(messageConstraints).build(); connManager.setDefaultConnectionConfig(connectionConfig); connManager.setConnectionConfig(new HttpHost("somehost", 80), ConnectionConfig.DEFAULT); connManager.setMaxTotal(100); connManager.setDefaultMaxPerRoute(10); connManager.setMaxPerRoute(new HttpRoute(new HttpHost("somehost", 80)), 20); CookieStore cookieStore = new BasicCookieStore(); CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); RequestConfig defaultRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BEST_MATCH) .setExpectContinueEnabled(true).setStaleConnectionCheckEnabled(true) .setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST)) .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).setConnectionRequestTimeout(3000) .setConnectTimeout(3000).setSocketTimeout(3000).build(); client = HttpClients.custom().setConnectionManager(connManager).setDefaultCookieStore(cookieStore) .setDefaultCredentialsProvider(credentialsProvider) // .setProxy(new HttpHost("myproxy", 8080)) .setDefaultRequestConfig(defaultRequestConfig).build(); }
From source file:com.offbynull.portmapper.pcp.PcpDiscovery.java
private static Set<InetAddress> discoverGateways() throws InterruptedException, IOException { final Set<InetAddress> foundGateways = Collections.synchronizedSet(new HashSet<InetAddress>()); Set<InetAddress> potentialGateways = NetworkUtils.getPotentialGatewayAddresses(); // port 5351 DatagramChannel unicastChannel = null; try {/* www . j a v a 2s . com*/ unicastChannel = DatagramChannel.open(); unicastChannel.configureBlocking(false); unicastChannel.socket().bind(new InetSocketAddress(0)); } catch (IOException ioe) { IOUtils.closeQuietly(unicastChannel); throw ioe; } UdpCommunicator communicator = null; try { communicator = new UdpCommunicator(Collections.singletonList(unicastChannel)); communicator.startAsync().awaitRunning(); communicator.addListener(new UdpCommunicatorListener() { @Override public void incomingPacket(InetSocketAddress sourceAddress, DatagramChannel channel, ByteBuffer packet) { foundGateways.add(sourceAddress.getAddress()); } }); ByteBuffer outBuf = ByteBuffer.allocate(1100); MapPcpRequest mpr = new MapPcpRequest(ByteBuffer.allocate(12), 0, 0, 0, InetAddress.getByName("::"), 0L); mpr.dump(outBuf, InetAddress.getByAddress(new byte[4])); // should get back an error for this, but this // should be fine because all we're looking for is a response, not // nessecarily a correct response -- self address being sent is // 0.0.0.0 (IPV4) // // also, we need to pass in MAP because Apple's garbage routers // give back NATPMP responses when you pass in ANNOUNCE outBuf.flip(); for (InetAddress potentialGateway : potentialGateways) { communicator.send(unicastChannel, new InetSocketAddress(potentialGateway, 5351), outBuf.asReadOnlyBuffer()); } Thread.sleep(5000L); } finally { if (communicator != null) { communicator.stopAsync().awaitTerminated(); } } foundGateways.retainAll(potentialGateways); // just incase we get back some unsolicited responses return new HashSet<>(foundGateways); }
From source file:com.vinexs.tool.NetworkManager.java
public static InetAddress intToInet(int value) { byte[] bytes = new byte[4]; for (int i = 0; i < 4; i++) { bytes[i] = byteOfInt(value, i);/*w w w .jav a 2 s .c o m*/ } try { return InetAddress.getByAddress(bytes); } catch (Exception e) { e.printStackTrace(); return null; } }
From source file:it.anyplace.sync.client.protocol.rp.RelayClient.java
public SessionInvitation getSessionInvitation(InetSocketAddress relaySocketAddress, String deviceId) throws Exception { logger.debug("connecting to relay = {} (temporary protocol mode)", relaySocketAddress); try (Socket socket = keystoreHandler.createSocket(relaySocketAddress, RELAY); RelayDataInputStream in = new RelayDataInputStream(socket.getInputStream()); RelayDataOutputStream out = new RelayDataOutputStream(socket.getOutputStream());) { {/*from w ww . j a va 2 s.co m*/ logger.debug("sending connect request for device = {}", deviceId); byte[] deviceIdData = deviceIdStringToHashData(deviceId); int lengthOfId = deviceIdData.length; out.writeHeader(CONNECT_REQUEST, 4 + lengthOfId); out.writeInt(lengthOfId); out.write(deviceIdData); out.flush(); } { logger.debug("receiving session invitation"); MessageReader messageReader = in.readMessage(); logger.debug("received message = {}", messageReader.dumpMessageForDebug()); checkArgument(messageReader.getType() == SESSION_INVITATION, "message type mismatch, expected %s, got %s", SESSION_INVITATION, messageReader.getType()); SessionInvitation.Builder builder = SessionInvitation.newBuilder(); builder.setFrom(hashDataToDeviceIdString(messageReader.readLengthAndData())); builder.setKey(BaseEncoding.base16().encode(messageReader.readLengthAndData())); byte[] address = messageReader.readLengthAndData(); if (address.length == 0) { builder.setAddress(socket.getInetAddress()); } else { InetAddress inetAddress = InetAddress.getByAddress(address); if (inetAddress.equals(InetAddress.getByName("0.0.0.0"))) { builder.setAddress(socket.getInetAddress()); } else { builder.setAddress(inetAddress); } } int zero = messageReader.getBuffer().getShort(); checkArgument(zero == 0, "expected 0, found %s", zero); int port = messageReader.getBuffer().getShort(); checkArgument(port > 0, "got invalid port value = %s", port); builder.setPort(port); int serverSocket = messageReader.getBuffer().getInt() & 1; builder.setServerSocket(serverSocket == 1); logger.debug("closing connection (temporary protocol mode)"); return builder.build(); } } }
From source file:org.opendaylight.controller.protocol_plugin.openflow.vendorextension.v6extension.V6Match.java
public V6Match(OFMatch match) { super();/*from ww w. j a va 2s. co m*/ this.match_len = 0; this.pad_size = 0; this.networkSourceMask = null; if (match.getNetworkSource() != 0) { InetAddress address = null; try { address = InetAddress.getByAddress(ByteBuffer.allocate(4).putInt(match.getNetworkSource()).array()); } catch (UnknownHostException e) { logger.error("", e); } this.setNetworkSource(address, null); } else { this.nwSrc = null; this.nwSrcState = MatchFieldState.MATCH_ABSENT; } this.networkDestinationMask = null; if (match.getNetworkDestination() != 0) { InetAddress address = null; try { address = InetAddress .getByAddress(ByteBuffer.allocate(4).putInt(match.getNetworkDestination()).array()); } catch (UnknownHostException e) { logger.error("", e); } this.setNetworkDestination(address, null); } else { this.nwDst = null; this.nwDstState = MatchFieldState.MATCH_ABSENT; } this.inputPortMask = 0; if (match.getInputPort() != 0) { this.setInputPort(match.getInputPort(), (short) 0); } else { this.inputPortMask = 0; this.inputPortState = MatchFieldState.MATCH_ABSENT; } this.dataLayerSourceMask = null; if (match.getDataLayerSource() != null) { this.setDataLayerSource(match.getDataLayerSource(), null); } else { this.dataLayerSource = null; this.dlSourceState = MatchFieldState.MATCH_ABSENT; } this.dataLayerDestinationMask = null; if (match.getDataLayerDestination() != null) { this.setDataLayerDestination(match.getDataLayerDestination(), null); } else { this.dataLayerDestination = null; this.dlDestState = MatchFieldState.MATCH_ABSENT; } this.dataLayerTypeMask = 0; if (match.getDataLayerType() != 0) { this.setDataLayerType(match.getDataLayerType(), (short) 0); } else { this.dataLayerType = 0; this.ethTypeState = MatchFieldState.MATCH_ABSENT; } this.dataLayerVirtualLanMask = 0; if (match.getDataLayerVirtualLan() != 0) { this.setDataLayerVirtualLan(match.getDataLayerVirtualLan(), (short) 0); } else { this.dataLayerVirtualLan = 0; this.dlVlanState = MatchFieldState.MATCH_ABSENT; } this.dataLayerVirtualLanPriorityCodePointMask = 0; if (match.getDataLayerVirtualLanPriorityCodePoint() != 0) { this.setDataLayerVirtualLanPriorityCodePoint(match.getDataLayerVirtualLanPriorityCodePoint(), (byte) 0); } else { this.dataLayerVirtualLanPriorityCodePoint = 0; } this.networkProtocolMask = 0; if (match.getNetworkProtocol() != 0) { this.setNetworkProtocol(this.networkProtocol = match.getNetworkProtocol(), (byte) 0); } else { this.networkProtocol = 0; this.nwProtoState = MatchFieldState.MATCH_ABSENT; } this.networkTypeOfServiceMask = 0; if (match.getNetworkTypeOfService() != 0) { this.setNetworkTypeOfService(this.networkTypeOfService = match.getNetworkTypeOfService(), (byte) 0); } else { this.networkTypeOfService = match.getNetworkTypeOfService(); this.nwTosState = MatchFieldState.MATCH_ABSENT; } this.transportSourceMask = 0; if (match.getTransportSource() != 0) { this.setTransportSource(match.getTransportSource(), (short) 0); } else { this.transportSource = 0; this.tpSrcState = MatchFieldState.MATCH_ABSENT; } this.transportDestinationMask = 0; if (match.getTransportDestination() != 0) { this.setTransportDestination(match.getTransportDestination(), (short) 0); } else { this.transportDestination = 0; this.tpDstState = MatchFieldState.MATCH_ABSENT; } this.setWildcards(match.getWildcards()); }