Validate an IP Address (with Mask)

wildcard mask calculator
ip calculator
validate ip address java
subnet mask
ip address pattern
spring validate ip address
ip address validation regex
valid ip address

I have ip addresses and a mask such as 10.1.1.1/32. I would like to check if 10.1.1.1 is inside that range. Is there a library or utility that would do this or do I need to write something myself?

First you'll want to convert your IP addresses into flat ints, which will be easier to work with:

String       s = "10.1.1.99";
Inet4Address a = (Inet4Address) InetAddress.getByName(s);
byte[]       b = a.getAddress();
int          i = ((b[0] & 0xFF) << 24) |
                 ((b[1] & 0xFF) << 16) |
                 ((b[2] & 0xFF) << 8)  |
                 ((b[3] & 0xFF) << 0);

Once you have your IP addresses as plain ints you can do some bit arithmetic to perform the check:

int subnet = 0x0A010100;   // 10.1.1.0/24
int bits   = 24;
int ip     = 0x0A010199;   // 10.1.1.99

// Create bitmask to clear out irrelevant bits. For 10.1.1.0/24 this is
// 0xFFFFFF00 -- the first 24 bits are 1's, the last 8 are 0's.
//
//     -1        == 0xFFFFFFFF
//     32 - bits == 8
//     -1 << 8   == 0xFFFFFF00
mask = -1 << (32 - bits)

if ((subnet & mask) == (ip & mask)) {
    // IP address is in the subnet.
}

Program to validate an IP address, C Program to find IP Address, Subnet Mask & Default Gateway � How to validate CVV number using Regular Expression � How to validate HTML� This free online IP subnet calculator covers both IPv4 and IPv6 protocols, providing information such as IP address, network address, subnet mask, IP range, and more. Also, explore hundreds of other math, financial, fitness, and health calculators.

public static boolean netMatch(String addr, String addr1){ //addr is subnet address and addr1 is ip address. Function will return true, if addr1 is within addr(subnet)

        String[] parts = addr.split("/");
        String ip = parts[0];
        int prefix;

        if (parts.length < 2) {
            prefix = 0;
        } else {
            prefix = Integer.parseInt(parts[1]);
        }

        Inet4Address a =null;
        Inet4Address a1 =null;
        try {
            a = (Inet4Address) InetAddress.getByName(ip);
            a1 = (Inet4Address) InetAddress.getByName(addr1);
        } catch (UnknownHostException e){}

        byte[] b = a.getAddress();
        int ipInt = ((b[0] & 0xFF) << 24) |
                         ((b[1] & 0xFF) << 16) |
                         ((b[2] & 0xFF) << 8)  |
                         ((b[3] & 0xFF) << 0);

        byte[] b1 = a1.getAddress();
        int ipInt1 = ((b1[0] & 0xFF) << 24) |
                         ((b1[1] & 0xFF) << 16) |
                         ((b1[2] & 0xFF) << 8)  |
                         ((b1[3] & 0xFF) << 0);

        int mask = ~((1 << (32 - prefix)) - 1);

        if ((ipInt & mask) == (ipInt1 & mask)) {
            return true;
        }
        else {
            return false;
        }
}

IP Calculator / IP Subnetting, A NetmaskValueError is raised if the mask is not valid for an IPv4 address. If strict is True and host bits are set in the supplied address, then ValueError is raised. 00001010 00001010 00001010 00001010 10.10.10.250. 11111111 11111111 11111111 11111010 255.255.255.0 network mask. ==========================. 00001010 00001010 00001010 00000000 10.10.10.0 network address. So when the network mask is set, both address will be considered to be on the same network.

Here is a version that takes subnet descriptions in several common ways, including IPv6.

Based on the other code posted here. On IPv4 addresses it might work slower than the approach of performing binary operations on bare int's.

package de.c3oe.tryanderror;
import java.math.BigInteger;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @author c3oe.de, based on snippets from Scott Plante, John Kugelmann
 */
public class Subnet
{
    final private int bytesSubnetCount;
    final private BigInteger bigMask;
    final private BigInteger bigSubnetMasked;

    /** For use via format "192.168.0.0/24" or "2001:db8:85a3:880:0:0:0:0/57" */
    public Subnet( final InetAddress subnetAddress, final int bits )
    {
        this.bytesSubnetCount = subnetAddress.getAddress().length; // 4 or 16
        this.bigMask = BigInteger.valueOf( -1 ).shiftLeft( this.bytesSubnetCount*8 - bits ); // mask = -1 << 32 - bits
        this.bigSubnetMasked = new BigInteger( subnetAddress.getAddress() ).and( this.bigMask );
    }

    /** For use via format "192.168.0.0/255.255.255.0" or single address */
    public Subnet( final InetAddress subnetAddress, final InetAddress mask )
    {
        this.bytesSubnetCount = subnetAddress.getAddress().length;
        this.bigMask = null == mask ? BigInteger.valueOf( -1 ) : new BigInteger( mask.getAddress() ); // no mask given case is handled here.
        this.bigSubnetMasked = new BigInteger( subnetAddress.getAddress() ).and( this.bigMask );
    }

    /**
     * Subnet factory method.
     * @param subnetMask format: "192.168.0.0/24" or "192.168.0.0/255.255.255.0"
     *      or single address or "2001:db8:85a3:880:0:0:0:0/57"
     * @return a new instance
     * @throws UnknownHostException thrown if unsupported subnet mask.
     */
    public static Subnet createInstance( final String subnetMask )
            throws UnknownHostException
    {
        final String[] stringArr = subnetMask.split("/");
        if ( 2 > stringArr.length )
            return new Subnet( InetAddress.getByName( stringArr[ 0 ] ), (InetAddress)null );
        else if ( stringArr[ 1 ].contains(".") || stringArr[ 1 ].contains(":") )
            return new Subnet( InetAddress.getByName( stringArr[ 0 ] ), InetAddress.getByName( stringArr[ 1 ] ) );
        else
            return new Subnet( InetAddress.getByName( stringArr[ 0 ] ), Integer.parseInt( stringArr[ 1 ] ) );
    }

    public boolean isInNet( final InetAddress address )
    {
        final byte[] bytesAddress = address.getAddress();
        if ( this.bytesSubnetCount != bytesAddress.length )
            return false;
        final BigInteger bigAddress = new BigInteger( bytesAddress );
        return  bigAddress.and( this.bigMask ).equals( this.bigSubnetMasked );
    }

    @Override
    final public boolean equals( Object obj )
    {
        if ( ! (obj instanceof Subnet) )
            return false;
        final Subnet other = (Subnet)obj;
        return  this.bigSubnetMasked.equals( other.bigSubnetMasked ) &&
                this.bigMask.equals( other.bigMask ) &&
                this.bytesSubnetCount == other.bytesSubnetCount;
    }

    @Override
    final public int hashCode()
    {
        return this.bytesSubnetCount;
    }

    @Override
    public String toString()
    {
        final StringBuilder buf = new StringBuilder();
        bigInteger2IpString( buf, this.bigSubnetMasked, this.bytesSubnetCount );
        buf.append( '/' );
        bigInteger2IpString( buf, this.bigMask, this.bytesSubnetCount );
        return buf.toString();
    }

    static private void bigInteger2IpString( final StringBuilder buf, final BigInteger bigInteger, final int displayBytes )
    {
        final boolean isIPv4 = 4 == displayBytes;
        byte[] bytes = bigInteger.toByteArray();
        int diffLen = displayBytes - bytes.length;
        final byte fillByte = 0 > (int)bytes[ 0 ] ? (byte)0xFF : (byte)0x00;

        int integer;
        for ( int i = 0; i < displayBytes; i++ )
        {
            if ( 0 < i && ! isIPv4 && i % 2 == 0 )
                buf.append( ':' );
            else if ( 0 < i && isIPv4 )
                buf.append( '.' );
            integer = 0xFF & (i < diffLen ? fillByte : bytes[ i - diffLen ]);
            if ( ! isIPv4 && 0x10 > integer )
                buf.append( '0' );
            buf.append( isIPv4 ? integer : Integer.toHexString( integer ) );
        }
    }
}

ipaddress — IPv4/IPv6 manipulation library — Python 3.8.5 , Write a function to check whether an input string is a valid IPv4 address or IPv6 address or neither. IPv4 addresses are canonically represented in dot-decimal� in my application users enter the ip address + sub net mask like this: 192.168.0.0/16 or 80.80.80.0/24 and i want to validate it like this: if the ip address is not a valid address then return false. (its easy and i can do it with IPAddress.TryParse method) if the ip address is not a public address

This is just a few lines of code with the open-source IPAddress Java library. Disclaimer: I am the project manager of the IPAddress library.

String subnetStr = "10.1.1.1/24";
String addrStr = "10.1.1.1";
IPAddress subnetAddress = new IPAddressString(subnetStr).getAddress();
IPAddress subnet = subnetAddress.toPrefixBlock();
IPAddress testAddress = new IPAddressString(addrStr).getAddress();
boolean result = subnet.contains(testAddress);
System.out.println(subnetAddress + " is in subnet " + subnet + " and " +
            (result ? "contains" : "does not contain") + " address " + testAddress);

Output:

10.1.1.1/24 is in subnet 10.1.1.0/24 and contains address 10.1.1.1

Validate IP Address, K. A. Garcia • 2 years ago. How can I include checking for subnet mask with 0-32 range? e. g. 192.168� An IPv6 address is represented as eight groups of four hexadecimal digits, each group is separated by a colon. Featured network tools; My IP - shows your computer IP address, that is seen by web servers and network. IP address is exposed to any network service (web, FTP, etc.). If behind router / firewall, then gateway address is shown.

There is commons-ip-math library that I believe does a very good job. Please note that as of May 2019, there hasn't been any updates to the library for 2 years (Could be that its already very mature library). Its available on maven-central

It supports working with both IPv4 and IPv6 addresses. Their brief documentation has examples on how you can check if an address is in a specific range for IPv4 and IPv6

Example for IPv4 range checking:

        String input1 = "10.1.1.1";
        Ipv4 ipv41 = Ipv4.parse(input1);

        // Using CIDR notation to specify the networkID and netmask
        Ipv4Range range = Ipv4Range.parse("10.1.1.1/32");
        boolean result = range.contains(ipv41);
        System.out.println(result); //true

        String input2 = "10.1.1.1";
        Ipv4 ipv42 = Ipv4.parse(input2);

        // Specifying the range with a start and end.
        Ipv4 start = Ipv4.of("10.1.1.1");
        Ipv4 end = Ipv4.of("10.1.1.1");
        range = Ipv4Range.from(start).to(end);

        result = range.contains(ipv42); //true
        System.out.println(result);

JavaScript : IP address validation, 0.15" is a valid IPV4 address. A newer IPV6 scheme, designed to eventually replace IPV4, uses a larger, more complex set of numbers mixed with other characters� Validate IP Address. Medium. 221 1151 Add to List Share. Write a function to check whether an input string is a valid IPv4 address or IPv6 address or neither.

What Makes an IP Address Invalid?, I don't fully understand how IP Address and Subnet mask work together. I am supposed to validate that two IP addresses are not in the same� The combination of IP address and subnet mask is invalid. All of the bits in the host address portion of the IP address are set to 1. Please enter a valid combination of IP address and subnet mask.

Validate IP Address with Subnet Mask - MSDN, 999.999 as if it were a valid IP address. If your regex flavor supports Unicode, it may even match ١٢٣.१२३.೧೨೩.๑๒๓. Whether this is a problem depends on the�

How to Find or Validate an IP Address, Dissecting an IP Address. IPv4 Addresses consist of 4 x octets separated by a dot (.) Why are they called octets? Because each valid number can�

Comments
  • possible duplicate of Does anyone know a java component to check if IP address is from particular network/netmask?
  • Assume I start with String ip = "10.1.1.1"; int mask = 24 how do I get 0x0A010100?
  • So there’s really no support for this in the base class library or some recommended third party netmask-handling package?
  • Would be useful to rewrite the solution also for IPv6 addresses
  • I used this with android to get the masked network address. But the result was wrong instead of 192.168.178.0 I got 0.178.168.192. You have to switch thw order of 24,16,8,0 to 0,8,16,24
  • I think it may be broken for bits = 0 ('/0' mask)