Java InetAddress to inetAddress2Int(InetAddress addr)

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

Description

Converts IPv4 InetAddress to 32 bits int.

License

Open Source License

Parameter

Parameter Description
addr IPv4 address object

Exception

Parameter Description
NullPointerException <tt>addr</tt> is <tt>null</tt>.
IllegalArgumentException the address is not IPv4 (Inet4Address).

Return

32 bits int

Declaration

public static final int inetAddress2Int(InetAddress addr) 

Method Source Code


//package com.java2s;
/*//from  ww w  . ja v  a2  s .  c  o m
 *   This file is part of dhcp4java, a DHCP API for the Java language.
 *   (c) 2006 Stephan Hadinger
 *
 *   This library is free software; you can redistribute it and/or
 *   modify it under the terms of the GNU Lesser General Public
 *   License as published by the Free Software Foundation; either
 *   version 2.1 of the License, or (at your option) any later version.
 *
 *   This library is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *   Lesser General Public License for more details.
 *
 *   You should have received a copy of the GNU Lesser General Public
 *   License along with this library; if not, write to the Free Software
 *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

import java.net.Inet4Address;
import java.net.InetAddress;

public class Main {
    /**
     * Converts IPv4 <tt>InetAddress</tt> to 32 bits int.
     * 
     * @param addr IPv4 address object
     * @return 32 bits int
     * @throws NullPointerException <tt>addr</tt> is <tt>null</tt>.
     * @throws IllegalArgumentException the address is not IPv4 (Inet4Address).
     */
    public static final int inetAddress2Int(InetAddress addr) {
        if (!(addr instanceof Inet4Address)) {
            throw new IllegalArgumentException("Only IPv4 supported");
        }

        byte[] addrBytes = addr.getAddress();
        return ((addrBytes[0] & 0xFF) << 24) | ((addrBytes[1] & 0xFF) << 16) | ((addrBytes[2] & 0xFF) << 8)
                | ((addrBytes[3] & 0xFF));
    }
}

Related

  1. addressToLong(InetAddress address)
  2. InetAddressToInt(InetAddress ip)
  3. inetAddressToThriftBinary(InetAddress inetAddress)
  4. ipv4AddressToInt(InetAddress addr)
  5. str(InetAddress address)