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

The following examples show how to use java.net.InetAddress#getAddress() . 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 want to check out the right sidebar which shows the related API usage.
Example 1
/**
 * Generates an engine Id based on an InetAddress. Handles IPv4 and IPv6 addresses. The creation algorithm uses the passed IANA number.
 * @param iana Your enterprise IANA number.
 * @param addr The IP address the SNMPv3 Adaptor Server is listening to.
 * @return The generated engine Id.
 * @since 1.5
 * @exception UnknownHostException if the provided <CODE>InetAddress </CODE> is null.
 */
public static SnmpEngineId createEngineId(int iana, InetAddress addr)
{
    if(addr == null) throw new IllegalArgumentException("InetAddress is null.");
    byte[] address = addr.getAddress();
    byte[] engineid = new byte[5 + address.length];
    engineid[0] = (byte) ( (iana & 0xFF000000) >> 24 );
    engineid[0] |= 0x80;
    engineid[1] = (byte) ( (iana & 0x00FF0000) >> 16 );
    engineid[2] = (byte) ( (iana & 0x0000FF00) >> 8 );

    engineid[3] = (byte) (iana & 0x000000FF);
    if(address.length == 4)
        engineid[4] = 0x01;

    if(address.length == 16)
        engineid[4] = 0x02;

    for(int i = 0; i < address.length; i++) {
        engineid[i + 5] = address[i];
    }

    return new SnmpEngineId(engineid);
}
 
Example 2
Source Project: ftpproxy   File: Subnet.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates a <code>Subnet</code> object from the specified
 * address and subnet mask.
 *
 * @param inetAddr the address
 * @param d the subnet mask represented as the number of significant
 *               bits (0 through 32)
 */
public Subnet(InetAddress inetAddr, short d) {
        if (d > 32) {
            throw new IllegalArgumentException("Invalid format: " + d);
        }

    this.addr = inetAddr.getAddress();

    int m = (0xFFFFFFFF << d) & 0xFFFFFFFF;

    this.mask = new byte[4];
    for (int i = 0; i < 4; i++) {
        mask[i] = (byte) ((m >> 8 * (3 - i)) & 0xFF);
        addr[i] = (byte) (addr[i] & mask[i]);
    }
 }
 
Example 3
private static Bytes encodeIp(final InetAddress addr) {
  // InetAddress deals with giving us the right number of bytes
  final byte[] address = addr.getAddress();
  final byte[] res = new byte[32];
  if (address.length == 4) {
    // lead with 10 bytes of 0's
    // then 2 bytes of 1's
    res[10] = (byte) 0xFF;
    res[11] = (byte) 0xFF;
    // then the ipv4
    System.arraycopy(address, 0, res, 12, 4);
  } else {
    System.arraycopy(address, 0, res, 0, address.length);
  }
  return Bytes.wrap(res);
}
 
Example 4
private byte[] getAddrBytes(InetAddress addr) throws GSSException {
    int addressType = getAddrType(addr);
    byte[] addressBytes = addr.getAddress();
    if (addressBytes != null) {
        switch (addressType) {
            case CHANNEL_BINDING_AF_INET:
                if (addressBytes.length != Inet4_ADDRSZ) {
                    throw new GSSException(GSSException.FAILURE, -1,
                    "Incorrect AF-INET address length in ChannelBinding.");
                }
                return (addressBytes);
            case CHANNEL_BINDING_AF_INET6:
                if (addressBytes.length != Inet6_ADDRSZ) {
                    throw new GSSException(GSSException.FAILURE, -1,
                    "Incorrect AF-INET6 address length in ChannelBinding.");
                }
                return (addressBytes);
            default:
                throw new GSSException(GSSException.FAILURE, -1,
                "Cannot handle non AF-INET addresses in ChannelBinding.");
        }
    }
    return null;
}
 
Example 5
Source Project: open-rmbt   File: Helperfunctions.java    License: Apache License 2.0 6 votes vote down vote up
public static String anonymizeIp(final InetAddress inetAddress)
{
    try
    {
        final byte[] address = inetAddress.getAddress();
        address[address.length - 1] = 0;
        if (address.length > 4) // ipv6
        {
            for (int i = 6; i < address.length; i++)
                address[i] = 0;
        }
        
        String result = InetAddresses.toAddrString(InetAddress.getByAddress(address));
        if (address.length == 4)
            result = result.replaceFirst(".0$", "");
        return result;
    }
    catch (final Exception e)
    {
        e.printStackTrace();
        return null;
    }
}
 
Example 6
Source Project: armeria   File: Inet4AddressBlock.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean test(InetAddress address) {
    requireNonNull(address, "address");
    if (maskBits == 0) {
        return true;
    }

    final byte[] bytes;
    if (address instanceof Inet6Address) {
        bytes = ipv6ToIpv4Address((Inet6Address) address);
    } else {
        bytes = address.getAddress();
    }
    if (bytes == null) {
        return false;
    }

    final int addr = ipv4AddressToInt(bytes);
    return addr >= lowerBound && addr <= upperBound;
}
 
Example 7
Source Project: mldht   File: Database.java    License: Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Generate a write token, which will give peers write access to the DB.
 * 
 * @param ip
 *            The IP of the peer
 * @param port
 *            The port of the peer
 * @return A Key
 */
ByteWrapper genToken(Key nodeId, InetAddress ip, int port, Key lookupKey) {
	updateTokenTimestamps();
	
	byte[] tdata = new byte[Key.SHA1_HASH_LENGTH + ip.getAddress().length + 2 + 8 + Key.SHA1_HASH_LENGTH + sessionSecret.length];
	// generate a hash of the ip port and the current time
	// should prevent anybody from crapping things up
	ByteBuffer bb = ByteBuffer.wrap(tdata);
	nodeId.toBuffer(bb);
	bb.put(ip.getAddress());
	bb.putShort((short) port);
	bb.putLong(timestampCurrent.get());
	lookupKey.toBuffer(bb);
	bb.put(sessionSecret);
	
	// shorten 4bytes to not waste packet size
	// the chance of guessing correctly would be 1 : 4 million and only be valid for a single infohash
	byte[] token = Arrays.copyOf(ThreadLocalUtils.getThreadLocalSHA1().digest(tdata), 4);
	
	
	return new ByteWrapper(token);
}
 
Example 8
@Override
public boolean match(Action action, InetAddress address, int port) {
    if (action != action())
        return false;
    byte[] candidate = address.getAddress();
    // same address type?
    if (candidate.length != addressAsBytes.length)
        return false;
    // check bytes
    for (int i=0; i<prefixByteCount; i++) {
        if (candidate[i] != addressAsBytes[i])
            return false;
    }
    // check remaining bits
    if ((prefixByteCount < addressAsBytes.length) &&
        ((candidate[prefixByteCount] & mask) !=
         (addressAsBytes[prefixByteCount] & mask)))
            return false;
    return super.match(action, address, port);
}
 
Example 9
Source Project: bt   File: Database.java    License: Apache License 2.0 5 votes vote down vote up
private boolean checkToken(ByteWrapper toCheck, Key nodeId, InetAddress ip, int port, Key lookupKey, long timeStamp) {

		byte[] tdata = new byte[Key.SHA1_HASH_LENGTH + ip.getAddress().length + 2 + 8 + Key.SHA1_HASH_LENGTH + sessionSecret.length];
		ByteBuffer bb = ByteBuffer.wrap(tdata);
		nodeId.toBuffer(bb);
		bb.put(ip.getAddress());
		bb.putShort((short) port);
		bb.putLong(timeStamp);
		bb.put(lookupKey.getHash());
		bb.put(sessionSecret);
		
		byte[] rawToken = Arrays.copyOf(ThreadLocalUtils.getThreadLocalSHA1().digest(tdata), 4);
		
		return toCheck.equals(new ByteWrapper(rawToken));
	}
 
Example 10
/**
* Compares this group to the specified object. Returns true if the object
* passed in matches the group represented.
*
* @param p the object to compare with.
* @return true if the object passed in matches the subnet mask,
*    false otherwise.
*/
 public boolean equals (Object p) {
     if (p instanceof PrincipalImpl || p instanceof NetMaskImpl){
         PrincipalImpl received = (PrincipalImpl) p;
         InetAddress addr = received.getAddress();
         if (SNMP_LOGGER.isLoggable(Level.FINEST)) {
             SNMP_LOGGER.logp(Level.FINEST, NetMaskImpl.class.getName(), "equals",
                 "Received Address : " + addr);
         }
         byte[] recAddr = addr.getAddress();
         for(int i = 0; i < subnet.length; i++) {
             if (SNMP_LOGGER.isLoggable(Level.FINEST)) {
                 SNMP_LOGGER.logp(Level.FINEST, NetMaskImpl.class.getName(), "equals",
                     "(recAddr[i]) : " + (recAddr[i] & 0xFF));
                 SNMP_LOGGER.logp(Level.FINEST, NetMaskImpl.class.getName(), "equals",
                     "(recAddr[i] & subnet[i]) : " +
                      ((recAddr[i] & (int)subnet[i]) &0xFF) +
                      " subnet[i] : " + (subnet[i] &0xFF));
             }
             if((recAddr[i] & subnet[i]) != subnet[i]) {
                 if (SNMP_LOGGER.isLoggable(Level.FINEST)) {
                     SNMP_LOGGER.logp(Level.FINEST, NetMaskImpl.class.getName(), "equals",
                         "FALSE");
                 }
                 return false;
             }
         }
         if (SNMP_LOGGER.isLoggable(Level.FINEST)) {
             SNMP_LOGGER.logp(Level.FINEST, NetMaskImpl.class.getName(), "equals",
                 "TRUE");
         }
         return true;
     } else
         return false;
 }
 
Example 11
Source Project: atomix   File: MessageEncoderV1.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void encodeAddress(ProtocolMessage message, ByteBuf buffer) {
  final InetAddress senderIp = address.address();
  final byte[] senderIpBytes = senderIp.getAddress();
  buffer.writeByte(senderIpBytes.length);
  buffer.writeBytes(senderIpBytes);
  buffer.writeInt(address.port());
}
 
Example 12
Source Project: h2o-2   File: UserSpecifiedNetwork.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Test if an internet address lives on this user specified network.
 * @param ia Address to test.
 * @return true if the address is on the network; false otherwise.
 */
public boolean inetAddressOnNetwork(InetAddress ia) {
  int i = (_o1 << 24) |
          (_o2 << 16) |
          (_o3 << 8) |
          (_o4 << 0);

  byte[] barr = ia.getAddress();
  if (barr.length != 4) {
    return false;
  }

  int j = (((int)barr[0] & 0xff) << 24) |
          (((int)barr[1] & 0xff) << 16) |
          (((int)barr[2] & 0xff) << 8) |
          (((int)barr[3] & 0xff) << 0);

  // Do mask math in 64-bit to handle 32-bit wrapping cases.
  long mask1 = ((long)1 << (32 - _bits));
  long mask2 = mask1 - 1;
  long mask3 = ~mask2;
  int mask4 = (int) (mask3 & 0xffffffff);

  if ((i & mask4) == (j & mask4)) {
    return true;
  }

  return false;
}
 
Example 13
Source Project: T0rlib4j   File: Socks5Message.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Construct client request or server response.
 * 
 * @param cmd
 *            - Request/Response code.
 * @param ip
 *            - IP field.
 * @paarm port - port field.
 */
public Socks5Message(int cmd, InetAddress ip, int port) {
	super(cmd, ip, port);

	if (ip == null) {
		this.host = "0.0.0.0";
	} else {
		this.host = ip.getHostName();
	}

	this.version = SOCKS_VERSION;

	byte[] addr;

	if (ip == null) {
		addr = new byte[4];
		addr[0] = addr[1] = addr[2] = addr[3] = 0;
	} else {
		addr = ip.getAddress();
	}

	if (addr.length == 4) {
		addrType = SOCKS_ATYP_IPV4;
	} else {
		addrType = SOCKS_ATYP_IPV6;
	}

	data = new byte[6 + addr.length];
	data[0] = (byte) SOCKS_VERSION; // Version
	data[1] = (byte) command; // Command
	data[2] = (byte) 0; // Reserved byte
	data[3] = (byte) addrType; // Address type

	// Put Address
	System.arraycopy(addr, 0, data, 4, addr.length);
	// Put port
	data[data.length - 2] = (byte) (port >> 8);
	data[data.length - 1] = (byte) (port);
}
 
Example 14
/**
 * Returns true if the InetAddress is either 255.255.255.255 for IPv4 or
 * ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff for IPv6.
 *
 * @return true if the InetAddress is either 255.255.255.255 for IPv4 or
 *     ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff for IPv6
 * @since 10.0
 */


public static boolean isMaximum(InetAddress address) {
  byte[] addr = address.getAddress();
  for (int i = 0; i < addr.length; i++) {
    if (addr[i] != (byte) 0xff) {
      return false;
    }
  }
  return true;
}
 
Example 15
@Override
public int compare(InetAddress a, InetAddress b)
{
  byte []bytesA = a.getAddress();
  byte []bytesB = b.getAddress();
  
  if (bytesA[0] == bytesB[0]) {
  }
  else if (bytesA[0] == 0) {
    return 1;
  }
  else if (bytesB[0] == 0) {
    return -1;
  }
  else if (bytesA[0] == 127) {
    return 1;
  }
  else if (bytesB[0] == 127) {
    return -1;
  }
  
  if (bytesA.length != bytesB.length) {
    return bytesA.length - bytesB.length;
  }
  
  for (int i = 0; i < bytesA.length; i++) {
    if (bytesA[i] != bytesB[i]) {
      return bytesA[i] - bytesB[i];
    }
  }

  return 0;
}
 
Example 16
/**
 * Test properties of an instance of InetAddress obtained via getLocalHost()
 * @param localHost
 * @param response
 * @throws IOException
 * @throws AssertionFailedException
 */
private static void testLocalHost(InetAddress localHost, HttpServletResponse response)
    throws IOException, AssertionFailedException {
  assertNotNull("localhost", localHost, response);
  assertTrue("instanceof Inet4Addr", localHost instanceof Inet4Address, response);

  //getAddress
  byte[] bytes = localHost.getAddress();
  assertNotNull("localhost address-bytes", bytes, response);
  assertEquals("localhost address bytes.length", 4, bytes.length, response);
  assertEquals("first byte of localhost address", 127, bytes[0], response);
  assertEquals("last byte of localhost address", 1, bytes[3], response);

  String name = localHost.getCanonicalHostName();
  assertEquals("getCanonicalHostName", "localhost", name, response);

  //getHostAddress should return the loopback address
  String address = localHost.getHostAddress();
  assertEquals("getHostAddress", "127.0.0.1", address, response);

  //getHostName
  name = localHost.getHostName();
  assertEquals("getHostName", "localhost", name, response);

  //Misc Properties
  assertFalse("isAnyLocalAddress", localHost.isAnyLocalAddress(), response);
  assertFalse("isLinkLocalAddress", localHost.isLinkLocalAddress(), response);
  assertTrue("isLoopbackAddress", localHost.isLoopbackAddress(), response);
  assertFalse("isLoopbackAddress", localHost.isMCGlobal(), response);
  assertFalse("isMCLinkLocal", localHost.isMCLinkLocal(), response);
  assertFalse("isMCNodeLocal", localHost.isMCNodeLocal(), response);
  assertFalse("isMCOrgLocal", localHost.isMCOrgLocal(), response);
  assertFalse("isMCSiteLocal", localHost.isMCSiteLocal(), response);
  assertFalse("isMulticastAddress", localHost.isMulticastAddress(), response);
  assertFalse("isSiteLocalAddress", localHost.isSiteLocalAddress(), response);

  //toString
  String s = localHost.toString();
  assertEquals("toString", "localhost/127.0.0.1", s, response);

  //isReachable
  assertFalse("isReachable", localHost.isReachable(1000), response);
  //Can't test version of isReachable() that takes a NetworkInterface
  //because it is not possible to get a network interface without triggering the ptrace sandbox
  //localHost.isReachable(netif,  ttl,  timeout);

}
 
Example 17
Source Project: flink   File: ConnectionUtils.java    License: 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;
}
 
Example 18
public HostAddress() throws UnknownHostException {
    InetAddress inetAddress = getLocalInetAddress();
    addrType = getAddrType(inetAddress);
    address = inetAddress.getAddress();
}
 
Example 19
/**
 * Constructs a new <CODE>SnmpString</CODE> from the specified <CODE> InetAddress </Code>.
 * @param address The <CODE>InetAddress </CODE>.
 *
 * @since 1.5
 */
public SnmpString(InetAddress address) {
    value = address.getAddress();
}
 
Example 20
/**
 * Constructs a new <CODE>SnmpString</CODE> from the specified <CODE> InetAddress </Code>.
 * @param address The <CODE>InetAddress </CODE>.
 *
 * @since 1.5
 */
public SnmpString(InetAddress address) {
    value = address.getAddress();
}