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

The following are Jave code examples for showing how to use getAddress() of the java.net.InetAddress class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: OpenJSharp   File: SnmpEngineId.java   Source Code and License Vote up 6 votes
/**
 * 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
Project: mac-address-detector-java   File: MacAddressHelper.java   Source Code and License Vote up 6 votes
/**
 * select a most suitable network interface according to the address
 *
 * @param address
 * @return
 */
private SelectedInterface _selectSuitableNetworkInterface(InetAddress address) {
    int similiarBytes = Integer.MIN_VALUE;
    SelectedInterface selectedInterface = new SelectedInterface();

    byte[] inputIpInBytes = address.getAddress();
    for (PcapNetworkInterface currentInterface : _localPcapNetworkInterfaces) {
        List<PcapAddress> addresses = currentInterface.getAddresses();
        if (addresses != null) {
            for (PcapAddress ipAddress : addresses) {
                // make sure the address should be same type, all ipv4 or all ipv6
                if (!_isSameTypeAddress(address, ipAddress.getAddress())) {
                    continue;
                }
                byte[] ipInBytes = ipAddress.getAddress().getAddress();
                int currentSimiliarBytes = _similarBytes(inputIpInBytes, ipInBytes);
                if (currentSimiliarBytes > similiarBytes) {
                    selectedInterface._selectedNetworkInterface = currentInterface;
                    selectedInterface._selectedIpAddress = ipAddress.getAddress();
                    similiarBytes = currentSimiliarBytes;
                }
            }
        }
    }
    return selectedInterface;
}
 
Example 3
Project: ChronoBike   File: Blowfish.java   Source Code and License Vote up 6 votes
public Blowfish(String csKey, boolean bMixWithIpAdress)
{
	try
	{
		if(bMixWithIpAdress)
		{
			InetAddress adr = InetAddress.getLocalHost();
			byte ipAdress[] = adr.getAddress();
			int nVal = 0;
			for(int n=0; n<ipAdress.length; n++)
			{
				nVal *= 256;
				nVal += ipAdress[n];
			}
			csKey += nVal;
		}
	}
	catch (UnknownHostException e)
	{
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	m_csKey = csKey;
}
 
Example 4
Project: googles-monorepo-demo   File: InetAddresses.java   Source Code and License Vote up 6 votes
/**
 * Returns the string representation of an {@link InetAddress}.
 *
 * <p>For IPv4 addresses, this is identical to {@link InetAddress#getHostAddress()}, but for IPv6
 * addresses, the output follows <a href="http://tools.ietf.org/html/rfc5952">RFC 5952</a> section
 * 4. The main difference is that this method uses "::" for zero compression, while Java's version
 * uses the uncompressed form.
 *
 * <p>This method uses hexadecimal for all IPv6 addresses, including IPv4-mapped IPv6 addresses
 * such as "::c000:201". The output does not include a Scope ID.
 *
 * @param ip {@link InetAddress} to be converted to an address string
 * @return {@code String} containing the text-formatted IP address
 * @since 10.0
 */
public static String toAddrString(InetAddress ip) {
  checkNotNull(ip);
  if (ip instanceof Inet4Address) {
    // For IPv4, Java's formatting is good enough.
    return ip.getHostAddress();
  }
  checkArgument(ip instanceof Inet6Address);
  byte[] bytes = ip.getAddress();
  int[] hextets = new int[IPV6_PART_COUNT];
  for (int i = 0; i < hextets.length; i++) {
    hextets[i] = Ints.fromBytes((byte) 0, (byte) 0, bytes[2 * i], bytes[2 * i + 1]);
  }
  compressLongestRunOfZeroes(hextets);
  return hextetsToIPv6String(hextets);
}
 
Example 5
Project: OpenJSharp   File: SdpProvider.java   Source Code and License Vote up 6 votes
@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 6
Project: parabuild-ci   File: WebcamMessage.java   Source Code and License Vote up 6 votes
public static String getIP3(){
	try {
		InetAddress addr = InetAddress.getLocalHost();
		byte[] ipAddr = addr.getAddress();
		addr = InetAddress.getByName(addr.getHostName());
		ipAddr = addr.getAddress();
    
        String ipAddrStr = "";
        for (int i=0; i<ipAddr.length; i++) {
            if (i > 0) {
                ipAddrStr += ".";
            }
            ipAddrStr += ipAddr[i]&0xFF;
        }
        return ipAddrStr;
    } catch (UnknownHostException e) {
    	
    }
    return null;
}
 
Example 7
Project: hashsdn-controller   File: NetUtils.java   Source Code and License Vote up 6 votes
/**
 * Given an IP address and a prefix network mask length, it returns the
 * equivalent subnet prefix IP address Example: for ip = "172.28.30.254" and
 * maskLen = 25 it will return "172.28.30.128"
 *
 * @param ip
 *            the IP address in InetAddress form
 * @param maskLen
 *            the length of the prefix network mask
 * @return the subnet prefix IP address in InetAddress form
 */
public static InetAddress getSubnetPrefix(final InetAddress ip, final int maskLen) {
    int bytes = maskLen / 8;
    int bits = maskLen % 8;
    byte modifiedByte;
    byte[] sn = ip.getAddress();
    if (bits > 0) {
        modifiedByte = (byte) (sn[bytes] >> 8 - bits);
        sn[bytes] = (byte) (modifiedByte << 8 - bits);
        bytes++;
    }
    for (; bytes < sn.length; bytes++) {
        sn[bytes] = (byte) 0;
    }
    try {
        return InetAddress.getByAddress(sn);
    } catch (final UnknownHostException e) {
        return null;
    }
}
 
Example 8
Project: jrpip   File: RequestId.java   Source Code and License Vote up 6 votes
private static int createClientIp()
{
    long time = System.currentTimeMillis();
    time &= 0xffffffffL;

    int clientIp;
    try
    {
        InetAddress inetadr = InetAddress.getLocalHost();
        byte[] tmp = inetadr.getAddress();
        clientIp = ((tmp[3] * 255 + tmp[2]) * 255 + tmp[1]) * 255 + tmp[0];
    }
    catch (Exception e)
    {
        // let's just fill it with something random:
        clientIp = (int) (Math.random() * Integer.MAX_VALUE);
    }
    clientIp ^= (int) time;
    return clientIp;
}
 
Example 9
Project: guava-mock   File: InetAddresses.java   Source Code and License Vote up 5 votes
/**
 * Returns a new InetAddress that is one more than the passed in address. This method works for
 * both IPv4 and IPv6 addresses.
 *
 * @param address the InetAddress to increment
 * @return a new InetAddress that is one more than the passed in address
 * @throws IllegalArgumentException if InetAddress is at the end of its range
 * @since 10.0
 */
public static InetAddress increment(InetAddress address) {
  byte[] addr = address.getAddress();
  int i = addr.length - 1;
  while (i >= 0 && addr[i] == (byte) 0xff) {
    addr[i] = 0;
    i--;
  }

  checkArgument(i >= 0, "Incrementing %s would wrap.", address);

  addr[i]++;
  return bytesToInetAddress(addr);
}
 
Example 10
Project: T0rlib4Android   File: Socks5Message.java   Source Code and License Vote up 5 votes
/**
 * 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 11
Project: TPlayer   File: WifiManagerStub.java   Source Code and License Vote up 5 votes
private static int InetAddress_to_hex(InetAddress a) {
    int result = 0;
    byte b[] = a.getAddress();
    for (int i = 0; i < 4; i++)
        result |= (b[i] & 0xff) << (8 * i);
    return result;
}
 
Example 12
Project: guava-mock   File: InetAddresses.java   Source Code and License Vote up 5 votes
/**
 * 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 13
Project: T0rlib4j   File: InetRange.java   Source Code and License Vote up 5 votes
static long ip2long(final InetAddress ip) {
	long l = 0;
	final byte[] addr = ip.getAddress();

	if (addr.length == 4) { // IPV4
		for (int i = 0; i < 4; ++i) {
			l += (((long) addr[i] & 0xFF) << 8 * (3 - i));
		}
	} else { // IPV6
		return 0; // Have no idea how to deal with those
	}
	return l;
}
 
Example 14
Project: T0rlib4Android   File: Socks4Message.java   Source Code and License Vote up 5 votes
/**
 * Most general constructor
 */
public Socks4Message(final int version, final int cmd,
		final InetAddress ip, final int port, final String user) {

	super(cmd, ip, port);
	this.user = user;
	this.version = version;

	msgLength = user == null ? 8 : 9 + user.length();
	msgBytes = new byte[msgLength];

	msgBytes[0] = (byte) version;
	msgBytes[1] = (byte) command;
	msgBytes[2] = (byte) (port >> 8);
	msgBytes[3] = (byte) port;

	byte[] addr;

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

	if (user != null) {
		final byte[] buf = user.getBytes();
		System.arraycopy(buf, 0, msgBytes, 8, buf.length);
		msgBytes[msgBytes.length - 1] = 0;
	}
}
 
Example 15
Project: hashsdn-controller   File: NetUtils.java   Source Code and License Vote up 5 votes
/**
 * Returns true if the passed InetAddress contains all zero
 *
 * @param ip
 *            the IP address to test
 * @return true if the address is all zero
 */
public static boolean isAny(final InetAddress ip) {
    for (byte b : ip.getAddress()) {
        if (b != 0) {
            return false;
        }
    }
    return true;
}
 
Example 16
Project: CleanBT   File: UtilsTest.java   Source Code and License Vote up 5 votes
@org.junit.Test
public void intToBytes() throws Exception {
    assertArrayEquals(Utils.int2Bytes(1), new byte[]{0, 0, 0, 1});
    InetAddress addr = InetAddress.getByName("82.221.103.244");
    byte[] address = addr.getAddress();

    assertEquals(addr, InetAddress.getByAddress(address));
}
 
Example 17
Project: cas4.0.x-server-wechat   File: RemoteAddressAuthenticationHandler.java   Source Code and License Vote up 5 votes
/**
 * Checks if a subnet contains a specific IP address.
 *
 * @param network The network address.
 * @param netmask The subnet mask.
 * @param ip The IP address to check.
 * @return A boolean value.
 */
private boolean containsAddress(final InetAddress network, final InetAddress netmask, final InetAddress ip) {
    logger.debug("Checking IP address: {} in ", ip, network, netmask);

    byte[] networkBytes = network.getAddress();
    byte[] netmaskBytes = netmask.getAddress();
    byte[] ipBytes = ip.getAddress();

    /* check IPv4/v6-compatibility or parameters: */
    if(networkBytes.length != netmaskBytes.length
            || netmaskBytes.length != ipBytes.length) {
        logger.debug("Network address {}, subnet mask {} and/or host address {}"
                + " have different sizes! (return false ...)", network, netmask, ip);
        return false;
    }

    /* Check if the masked network and ip addresses match: */
    for(int i=0; i<netmaskBytes.length; i++) {
        int mask = netmaskBytes[i] & 0xff;
        if((networkBytes[i] & mask) != (ipBytes[i] & mask)) {
            logger.debug("{} is not in {}/{}", ip, network, netmask);
            return false;
        }
    }
    logger.debug("{} is in {}/{}", ip, network, netmask);
    return true;
}
 
Example 18
Project: openjdk-jdk10   File: SdpProvider.java   Source Code and License Vote up 5 votes
AddressPortRangeRule(Action action, InetAddress address,
                     int prefix, int port, int end)
{
    super(action, port, end);
    this.addressAsBytes = address.getAddress();
    this.prefixByteCount = prefix >> 3;
    this.mask = (byte)(0xff << (8 - (prefix % 8)));
}
 
Example 19
Project: incubator-netbeans   File: IpAddressUtils.java   Source Code and License Vote up 4 votes
@Override
public int compare(InetAddress a1, InetAddress a2) {
    byte[] bArr1 = a1.getAddress();
    byte[] bArr2 = a2.getAddress();

    if ((a1 instanceof Inet4Address) && (a2 instanceof Inet6Address)) {
        return (ip4BeforeIp6) ? -1 : 1;
    }
    if ((a1 instanceof Inet6Address) && (a2 instanceof Inet4Address)) {
        return (ip4BeforeIp6) ? 1 : -1;
    }
    
    if (bArr1.length != bArr2.length) {
        // according to JDK spec, this shouldn't be possible
        // but we take no risks here. This could happen if one day
        // there are more sub-classes of InetAddress than just 
        // Inet4Address or Inet6Address.
        if (bArr1.length < bArr2.length) {
            return (ip4BeforeIp6) ? -1 : 1;
        } else {
            return (ip4BeforeIp6) ? 1 : -1;
        }
    }
    
    if (shallow) {
        return 0;
    }
    
    // Compare byte-by-byte.
    for (int i = 0; i < bArr1.length; i++) {
        int x1 = Byte.toUnsignedInt(bArr1[i]);
        int x2 = Byte.toUnsignedInt(bArr2[i]);
        
        if (x1 == x2) {
            continue;
        }
        if (x1 < x2) {
            return -1;
        } else {
            return 1;
        }
    }
    return 0;
}
 
Example 20
Project: OpenJSharp   File: HostAddress.java   Source Code and License Vote up 4 votes
public HostAddress() throws UnknownHostException {
    InetAddress inetAddress = getLocalInetAddress();
    addrType = getAddrType(inetAddress);
    address = inetAddress.getAddress();
}