Java Code Examples for java.net.InetAddress#getByAddress()
The following examples show how to use
java.net.InetAddress#getByAddress() .
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: SimpleNameService.java From TencentKona-8 with GNU General Public License v2.0 | 7 votes |
public InetAddress[] lookupAllHostAddr(String host) throws UnknownHostException { lookupCalls ++; String value = (String)hosts.get(host); if (value == null) { throw new UnknownHostException(host); } StringTokenizer st = new StringTokenizer(value, "."); byte addr[] = new byte[4]; for (int i=0; i<4; i++) { addr[i] = (byte)Integer.parseInt(st.nextToken()); } InetAddress[] res = new InetAddress[1]; res[0] = InetAddress.getByAddress(host, addr); return res; }
Example 2
Source File: DHTServerHandler.java From Dodder with MIT License | 6 votes |
/** * 解析响应内容中的 DHT 节点信息 * * @param r */ private void resolveNodes(Map r) { byte[] nodes = (byte[]) r.get("nodes"); if (nodes == null) return; for (int i = 0; i < nodes.length; i += 26) { try { //limit the node queue size if (NODES_QUEUE.size() > 5000) continue; InetAddress ip = InetAddress.getByAddress(new byte[]{nodes[i + 20], nodes[i + 21], nodes[i + 22], nodes[i + 23]}); InetSocketAddress address = new InetSocketAddress(ip, (0x0000FF00 & (nodes[i + 24] << 8)) | (0x000000FF & nodes[i + 25])); byte[] nid = new byte[20]; System.arraycopy(nodes, i, nid, 0, 20); NODES_QUEUE.offer(new Node(nid, address)); //log.info("get node address=[{}] ", address); } catch (Exception e) { log.error("", e); } } }
Example 3
Source File: GrpclbNameResolverTest.java From grpc-java with Apache License 2.0 | 6 votes |
@Test public void resolve_nullResourceResolver() throws Exception { InetAddress backendAddr = InetAddress.getByAddress(new byte[] {127, 0, 0, 0}); AddressResolver mockAddressResolver = mock(AddressResolver.class); when(mockAddressResolver.resolveAddress(anyString())) .thenReturn(Collections.singletonList(backendAddr)); ResourceResolver resourceResolver = null; resolver.setAddressResolver(mockAddressResolver); resolver.setResourceResolver(resourceResolver); resolver.start(mockListener); assertThat(fakeClock.runDueTasks()).isEqualTo(1); verify(mockListener).onResult(resultCaptor.capture()); ResolutionResult result = resultCaptor.getValue(); assertThat(result.getAddresses()) .containsExactly( new EquivalentAddressGroup(new InetSocketAddress(backendAddr, DEFAULT_PORT))); assertThat(result.getAttributes()).isEqualTo(Attributes.EMPTY); assertThat(result.getServiceConfig()).isNull(); }
Example 4
Source File: CIDRUtils.java From bidder with Apache License 2.0 | 5 votes |
private void calculate() throws UnknownHostException { ByteBuffer maskBuffer; int targetSize; if (inetAddress.getAddress().length == 4) { maskBuffer = ByteBuffer .allocate(4) .putInt(-1); targetSize = 4; } else { maskBuffer = ByteBuffer.allocate(16) .putLong(-1L) .putLong(-1L); targetSize = 16; } BigInteger mask = (new BigInteger(1, maskBuffer.array())).not().shiftRight(prefixLength); ByteBuffer buffer = ByteBuffer.wrap(inetAddress.getAddress()); BigInteger ipVal = new BigInteger(1, buffer.array()); BigInteger startIp = ipVal.and(mask); BigInteger endIp = startIp.add(mask.not()); byte[] startIpArr = toBytes(startIp.toByteArray(), targetSize); byte[] endIpArr = toBytes(endIp.toByteArray(), targetSize); this.startAddress = InetAddress.getByAddress(startIpArr); this.endAddress = InetAddress.getByAddress(endIpArr); }
Example 5
Source File: PeersMessage.java From Qora with MIT License | 5 votes |
public static PeersMessage parse(byte[] data) throws Exception { //READ LENGTH byte[] lengthBytes = Arrays.copyOfRange(data, 0, DATA_LENGTH); int length = Ints.fromByteArray(lengthBytes); //CHECK IF DATA MATCHES LENGTH if(data.length != DATA_LENGTH + (length * ADDRESS_LENGTH)) { throw new Exception("Data does not match length"); } //CREATE PEER LIST List<Peer> peers = new ArrayList<Peer>(); for(int i=0; i<length; i++) { //CALCULATE POSITION int position = lengthBytes.length + (i * ADDRESS_LENGTH); //READ ADDRESS byte[] addressBytes = Arrays.copyOfRange(data, position, position + ADDRESS_LENGTH); InetAddress address = InetAddress.getByAddress(addressBytes); //CREATE PEER Peer peer = new Peer(address); //ADD TO LIST peers.add(peer); } return new PeersMessage(peers); }
Example 6
Source File: TestInetAddressServlet.java From appengine-java-vm-runtime with Apache License 2.0 | 5 votes |
/** * Get instances of InetAddress by calling InetAddress.getByAddress(byte[]), * Inet4Address.getByAddress(byte[]), and Inet6Address.getByAddress(byte[]), * passing in a 4-byte address, * and then test their properties. * @param response HttpServletResponse used to return failure message * @throws IOException If method being tested throws this. * @throws AssertionFailedException If an assertion fails */ private static void testGetByAddress4(HttpServletResponse response) throws IOException, AssertionFailedException { byte[] addressBytes = new byte[] {74, 125, (byte) 224, 19}; String addressString = "74.125.224.19"; String name = null; InetAddress googleDotCom = InetAddress.getByAddress(addressBytes); testNameAndAddress4(name, addressString, addressBytes, googleDotCom, response); googleDotCom = Inet4Address.getByAddress(addressBytes); testNameAndAddress4(name, addressString, addressBytes, googleDotCom, response); googleDotCom = Inet6Address.getByAddress(addressBytes); testNameAndAddress4(name, addressString, addressBytes, googleDotCom, response); }
Example 7
Source File: HostAddress.java From openjdk-8-source with GNU General Public License v2.0 | 5 votes |
/** * Gets the InetAddress of this HostAddress. * @return the IP address for this specified host. * @exception if no IP address for the host could be found. * */ public InetAddress getInetAddress() throws UnknownHostException { // the type of internet addresses is 2. if (addrType == Krb5.ADDRTYPE_INET || addrType == Krb5.ADDRTYPE_INET6) { return (InetAddress.getByAddress(address)); } else { // if it is other type (ISO address, XNS address, etc) return null; } }
Example 8
Source File: IPAddress.java From msgpack-rpc-java with Apache License 2.0 | 5 votes |
public InetSocketAddress getInetSocketAddress() { try { return new InetSocketAddress(InetAddress.getByAddress(address), port); } catch (UnknownHostException e) { throw new RuntimeException(e.getMessage()); } }
Example 9
Source File: HostProvider.java From visualvm with GNU General Public License v2.0 | 5 votes |
public Host createUnknownHost() { try { return new Host("unknown", InetAddress.getByAddress(new byte[] { 0, 0, 0, 0 })) {}; // NOI18N } catch (UnknownHostException e) { LOGGER.severe("Failure: cannot resolve <unknown> host"); // NOI18N return null; } }
Example 10
Source File: NetworkUtils.java From android_9.0.0_r45 with Apache License 2.0 | 5 votes |
/** * Get InetAddress masked with prefixLength. Will never return null. * @param address the IP address to mask with * @param prefixLength the prefixLength used to mask the IP */ public static InetAddress getNetworkPart(InetAddress address, int prefixLength) { byte[] array = address.getAddress(); maskRawAddress(array, prefixLength); InetAddress netPart = null; try { netPart = InetAddress.getByAddress(array); } catch (UnknownHostException e) { throw new RuntimeException("getNetworkPart error - " + e.toString()); } return netPart; }
Example 11
Source File: Ip4.java From cidr-ip-trie with Mozilla Public License 2.0 | 5 votes |
/** * This method uses InetAddress.getByAddress, and so does not block. * * @return java.net.InetAddress representing this IPv4 address * @throws UnknownHostException if not host found */ 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]}); }
Example 12
Source File: IPAddresses.java From vespa with Apache License 2.0 | 5 votes |
static InetAddress prefixTranslate(byte[] address, byte[] prefix, int nofBytes) { System.arraycopy(prefix, 0, address, 0, nofBytes); try { return InetAddress.getByAddress(address); } catch (UnknownHostException e) { throw new UncheckedIOException(e); } }
Example 13
Source File: DoubleServerTest.java From simplejmx with ISC License | 4 votes |
@Test public void testJmxServer() throws Exception { JmxServer server1 = null; JmxServer server2 = null; JmxClient client1 = null; JmxClient client2 = null; TestObject testObject = new TestObject(); try { InetAddress serverAddr1 = InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 }); int serverPort1 = DEFAULT_PORT; server1 = new JmxServer(serverAddr1, serverPort1); InetAddress serverAddr2 = InetAddress.getLocalHost(); int serverPort2 = DEFAULT_PORT + 1; server2 = new JmxServer(serverAddr2, serverPort2); server1.start(); server2.start(); /* * NOTE: since the platform MbeanServer is used, this registers one both servers. */ server1.register(testObject); // Thread.sleep(1000000000); client1 = new JmxClient(serverAddr1, serverPort1); client2 = new JmxClient(serverAddr2, serverPort2); testClient(client1); testClient(client2); } finally { if (server1 != null) { server1.unregister(testObject); IoUtils.closeQuietly(server1); } if (server2 != null) { server2.unregister(testObject); IoUtils.closeQuietly(server2); } System.gc(); } }
Example 14
Source File: GrpclbNameResolverTest.java From grpc-java with Apache License 2.0 | 4 votes |
@Test public void resolve_presentResourceResolver() throws Exception { InetAddress backendAddr = InetAddress.getByAddress(new byte[] {127, 0, 0, 0}); InetAddress lbAddr = InetAddress.getByAddress(new byte[] {10, 1, 0, 0}); int lbPort = 8080; String lbName = "foo.example.com."; // original name in SRV record SrvRecord srvRecord = new SrvRecord(lbName, 8080); AddressResolver mockAddressResolver = mock(AddressResolver.class); when(mockAddressResolver.resolveAddress(hostName)) .thenReturn(Collections.singletonList(backendAddr)); when(mockAddressResolver.resolveAddress(lbName)) .thenReturn(Collections.singletonList(lbAddr)); ResourceResolver mockResourceResolver = mock(ResourceResolver.class); when(mockResourceResolver.resolveTxt(anyString())) .thenReturn( Collections.singletonList( "grpc_config=[{\"clientLanguage\": [\"java\"], \"serviceConfig\": {}}]")); when(mockResourceResolver.resolveSrv(anyString())) .thenReturn(Collections.singletonList(srvRecord)); when(serviceConfigParser.parseServiceConfig(ArgumentMatchers.<String, Object>anyMap())) .thenAnswer(new Answer<ConfigOrError>() { @Override public ConfigOrError answer(InvocationOnMock invocation) { Object[] args = invocation.getArguments(); return ConfigOrError.fromConfig(args[0]); } }); resolver.setAddressResolver(mockAddressResolver); resolver.setResourceResolver(mockResourceResolver); resolver.start(mockListener); assertThat(fakeClock.runDueTasks()).isEqualTo(1); verify(mockListener).onResult(resultCaptor.capture()); ResolutionResult result = resultCaptor.getValue(); InetSocketAddress resolvedBackendAddr = (InetSocketAddress) Iterables.getOnlyElement( Iterables.getOnlyElement(result.getAddresses()).getAddresses()); assertThat(resolvedBackendAddr.getAddress()).isEqualTo(backendAddr); EquivalentAddressGroup resolvedBalancerAddr = Iterables.getOnlyElement(result.getAttributes().get(GrpclbConstants.ATTR_LB_ADDRS)); assertThat(resolvedBalancerAddr.getAttributes().get(GrpclbConstants.ATTR_LB_ADDR_AUTHORITY)) .isEqualTo("foo.example.com"); InetSocketAddress resolvedBalancerSockAddr = (InetSocketAddress) Iterables.getOnlyElement(resolvedBalancerAddr.getAddresses()); assertThat(resolvedBalancerSockAddr.getAddress()).isEqualTo(lbAddr); assertThat(resolvedBalancerSockAddr.getPort()).isEqualTo(lbPort); assertThat(result.getServiceConfig().getConfig()).isNotNull(); verify(mockAddressResolver).resolveAddress(hostName); verify(mockResourceResolver).resolveTxt("_grpc_config." + hostName); verify(mockResourceResolver).resolveSrv("_grpclb._tcp." + hostName); }
Example 15
Source File: SocketPermission.java From Bytecoder with Apache License 2.0 | 4 votes |
/** * Initialize the SocketPermission object. We don't do any DNS lookups * as this point, instead we hold off until the implies method is * called. */ private void init(String host, int mask) { // Set the integer mask that represents the actions if ((mask & ALL) != mask) throw new IllegalArgumentException("invalid actions mask"); // always OR in RESOLVE if we allow any of the others this.mask = mask | RESOLVE; // Parse the host name. A name has up to three components, the // hostname, a port number, or two numbers representing a port // range. "www.example.com:8080-9090" is a valid host name. // With IPv6 an address can be 2010:836B:4179::836B:4179 // An IPv6 address needs to be enclose in [] // For ex: [2010:836B:4179::836B:4179]:8080-9090 // Refer to RFC 2732 for more information. int rb = 0 ; int start = 0, end = 0; int sep = -1; String hostport = host; if (host.charAt(0) == '[') { start = 1; rb = host.indexOf(']'); if (rb != -1) { host = host.substring(start, rb); } else { throw new IllegalArgumentException("invalid host/port: "+host); } sep = hostport.indexOf(':', rb+1); } else { start = 0; sep = host.indexOf(':', rb); end = sep; if (sep != -1) { host = host.substring(start, end); } } if (sep != -1) { String port = hostport.substring(sep+1); try { portrange = parsePort(port); } catch (Exception e) { throw new IllegalArgumentException("invalid port range: "+port); } } else { portrange = new int[] { PORT_MIN, PORT_MAX }; } hostname = host; // is this a domain wildcard specification if (host.lastIndexOf('*') > 0) { throw new IllegalArgumentException("invalid host wildcard specification"); } else if (host.startsWith("*")) { wildcard = true; if (host.equals("*")) { cname = ""; } else if (host.startsWith("*.")) { cname = host.substring(1).toLowerCase(); } else { throw new IllegalArgumentException("invalid host wildcard specification"); } return; } else { if (!host.isEmpty()) { // see if we are being initialized with an IP address. char ch = host.charAt(0); if (ch == ':' || Character.digit(ch, 16) != -1) { byte ip[] = IPAddressUtil.textToNumericFormatV4(host); if (ip == null) { ip = IPAddressUtil.textToNumericFormatV6(host); } if (ip != null) { try { addresses = new InetAddress[] {InetAddress.getByAddress(ip) }; init_with_ip = true; } catch (UnknownHostException uhe) { // this shouldn't happen invalid = true; } } } } } }
Example 16
Source File: TopoloyUpdateChecker.java From floodlight_with_topoguard with Apache License 2.0 | 4 votes |
Command processPacketInMessage(IOFSwitch sw, OFPacketIn pi, FloodlightContext cntx) { Ethernet eth = IFloodlightProviderService.bcStore.get(cntx, IFloodlightProviderService.CONTEXT_PI_PAYLOAD); long dpid = sw.getId(); short inport = pi.getInPort(); Port switch_port = new Port(dpid, inport); MACAddress src_mac = eth.getSourceMAC(); PortProperty pp = this.port_list.get(switch_port); if (pp == null) return Command.CONTINUE; DeviceType dt = pp.getDeviceType(); // testify if the packet is the response to Host Probing if (eth.isBroadcast()) return Command.CONTINUE; try { if (eth.getEtherType() == Ethernet.TYPE_IPv4){ IPv4 ip = (IPv4) eth.getPayload(); InetAddress srcIP = InetAddress.getByAddress( BigInteger.valueOf(ip.getSourceAddress()).toByteArray()); InetAddress dstIP = InetAddress.getByAddress( BigInteger.valueOf(ip.getDestinationAddress()).toByteArray()); if(ip.getProtocol() == IPv4.PROTOCOL_ICMP){ ICMP icmp = (ICMP) ip.getPayload(); if (icmp.getIcmpCode() == ICMP.ECHO_REPLY){ if (hostProber.probedPorts.containsKey(switch_port)){ for (HostEntity he : hostProber.probedPorts.get(switch_port)){ if (he.ip.equals(srcIP) && he.mac.equals(eth.getSourceMAC()) && InetAddress.getByName(ControllerIP).equals(dstIP)){ //we think this is the response to host probing //Violation: host is still reachable at previous locaiton logger.warn("Violation: Host Move from switch {} port {} is still reachable" , dpid, inport); List<HostEntity> hostEntity = hostProber.probedPorts.get(switch_port); hostEntity.remove(he); hostProber.probedPorts.put(switch_port, hostEntity); return Command.STOP; } } } } } } } catch (UnknownHostException e) { logger.error("Cannot construct InetAddress, {}", e.getMessage()); } // if the payload is lldp, we do not verify correctness of LLDP in this point if (eth.getPayload() instanceof LLDP) { if (dt == DeviceType.ANY) { pp.setPortSwitch(); } else if (dt == DeviceType.HOST) { // Violation: impossible to receive LLDP from HOST port, Countermeasure: eat the lldp logger.warn("Violation: Receive LLDP packets from HOST port: SW {} port {}" , dpid, inport); return Command.STOP; } } // if the payload is host traffic else { // if this host found before if (this.mac_port.containsKey(src_mac)) { Port host_location = this.mac_port.get(src_mac); if (host_location == switch_port) { // this port is first hop port for found host if (dt == DeviceType.SWITCH) { // Violation: receive first hop traffic from SWITH port logger.warn("Violation: Receive first hop host packets from SWITCH port: SW {} port {}" , dpid, inport); //return Command.STOP; } else if (dt == DeviceType.ANY) { //this happened if the port is shutdown pp.setPortHost(); pp.disableHostShutDown(src_mac); this.port_list.put(switch_port, pp); } } } else { // new host this.mac_port.put(src_mac, switch_port); pp.addHost(src_mac); pp.setPortAny(); this.port_list.put(switch_port, pp); } } return Command.CONTINUE; }
Example 17
Source File: SerializerUtils.java From cacheonix-core with GNU Lesser General Public License v2.1 | 4 votes |
public static InetAddress readInetAddress(final DataInput in, final boolean fixedLength) throws IOException { // Read boolean null value marker if (in.readBoolean()) { // The address is null if (fixedLength) { // Read padded bytes in.readByte(); in.readLong(); in.readLong(); } return null; } // Read the address final byte addrLength = in.readByte(); switch (addrLength) { case 4: final int address = in.readInt(); if (fixedLength) { // Pad 12 bytes in.readInt(); in.readLong(); } final byte[] addr = new byte[4]; addr[0] = (byte) (address >>> 24 & 0xFF); addr[1] = (byte) (address >>> 16 & 0xFF); addr[2] = (byte) (address >>> 8 & 0xFF); addr[3] = (byte) (address & 0xFF); return InetAddress.getByAddress(addr); case 16: final byte[] result = new byte[16]; in.readFully(result); return InetAddress.getByAddress(result); default: throw new IOException("Unknown address format, length: " + addrLength); } }
Example 18
Source File: FakeResolver.java From BUbiNG with Apache License 2.0 | 4 votes |
@Override public InetAddress[] resolve(final String hostname) throws UnknownHostException { if ("localhost".equals(hostname)) return Frontier.LOOPBACK; return new InetAddress[] { InetAddress.getByAddress(com.google.common.primitives.Ints.toByteArray(hostname.hashCode())) }; }
Example 19
Source File: NetworkAdminASNImpl.java From BiglyBT with GNU General Public License v2.0 | 3 votes |
protected InetAddress getCIDREndAddress() throws NetworkAdminException { int pos = bgp_prefix.indexOf('/'); try{ InetAddress start = InetAddress.getByName( bgp_prefix.substring(0,pos)); int cidr_mask = Integer.parseInt( bgp_prefix.substring( pos+1 )); byte[] bytes = start.getAddress(); for ( int i=cidr_mask;i<bytes.length*8;i++){ bytes[i/8] |= 1<<(7-(i%8)); } return( InetAddress.getByAddress( bytes )); }catch( Throwable e ){ throw( new NetworkAdminException( "Parse failure for '" + bgp_prefix + "'", e )); } }
Example 20
Source File: HostNameToIPResolver.java From BiglyBT with GNU General Public License v2.0 | 2 votes |
public static InetAddress syncResolve( String host ) throws UnknownHostException { if ( isNonDNSName( host )){ throw( new HostNameToIPResolverException( "non-DNS name '" + host + "'", true )); } // handle any raw addresses up front byte[] bytes = textToNumericFormat( host ); if ( bytes != null ){ return( InetAddress.getByAddress( bytes )); } // filter out partially complete raw addresses by applying the basic rule in ftp://ftp.is.co.za/rfc/rfc3696.txt // at least one dot + not all numeric char[] chars = host.toCharArray(); boolean resolve = false; for (int i=0;i<chars.length;i++){ if ( !( chars[i] == '.' || Character.isDigit(chars[i]))){ resolve = true; break; } } if ( resolve && host.startsWith( "websocket." )){ resolve = false; for (int i=10;i<chars.length;i++){ if ( !Character.isDigit(chars[i])){ resolve = true; break; } } } if ( resolve ){ return( InetAddress.getByName( host)); }else{ throw( new UnknownHostException( "Host '" + host + "' doesn't obey minimal validation rules")); } }