Java InetAddress to ipv4AddressToInt(InetAddress addr)

Here you can find the source of ipv4AddressToInt(InetAddress addr)

Description

Convert an IPv4 INET address to an integer.

License

Open Source License

Parameter

Parameter Description
addr IPv4 INET address.

Exception

Parameter Description
IllegalArgumentException if the address is really an IPv6 address

Return

integer representation of a given address.

Declaration

public static int ipv4AddressToInt(InetAddress addr) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.net.Inet6Address;
import java.net.InetAddress;

public class Main {
    /** /*from  w  ww . j  a v  a2  s .  com*/
     * Convert an IPv4 INET address to an integer.
     * @param addr   IPv4 INET address.
     * @return integer representation of a given address.
     * @throws IllegalArgumentException if the address is really an IPv6 address
     */
    public static int ipv4AddressToInt(InetAddress addr) {

        if (addr instanceof Inet6Address)
            throw new IllegalArgumentException("IPv6 address used in IPv4 context");

        byte[] a = addr.getAddress();

        int res = ((a[0] & 0xFF) << 24) | ((a[1] & 0xFF) << 16) | ((a[2] & 0xFF) << 8) | (a[3] & 0xFF);

        return res;
    }
}

Related

  1. addressToLong(InetAddress address)
  2. inetAddress2Int(InetAddress addr)
  3. InetAddressToInt(InetAddress ip)
  4. inetAddressToThriftBinary(InetAddress inetAddress)
  5. str(InetAddress address)
  6. toAddressString(InetAddress ip)
  7. toAddrString(InetAddress ip)
  8. toDotString(InetAddress ip)