Thursday 24 November 2022

How to check whether a string is valid IPv4 address or not?

Every machine in the network has a unique IP address. There are two types of IP addresses.

 

IPv4 address: IPv4 address is a 32 bit number. An IPv4 address is written in decimal digits, where each digit is separated by a dot (.) and has the values ranging from 0 to 255.

 

Ex:

12.32.0.128

 

IPv6 address: IPv6 is a 128 bit alpha numeric value that uniquely identify a device in the IPv6 network. IPv6 drastically increased the number of addresses, as compared to its successor IPv4.

 

IPv6 address is 128 bit in length, and divided into 8 groups, where each group is of 16 bits in length and separated by a colon (:).

 

Ex:

80AB:00DC:0000:0CDE:5678:1234:211E:820D

 

IPv6 address is split into two components.

a.   Network component: First 64 bits of the address specify the network component, and is used in routing.

b.   Node component: Later 64 bits of the address specify the node component, and is used to identify the address of the node.

 

Method signature to identify a IPv4 address

public static boolean isValidIpV4Address(String ipAddress)

 


Find the below working application.

 

IPv4AddressCheck.java

package com.sample.app;

public class IPv4AddressCheck {

	/**
	 * 
	 * @param ipAddress
	 * 
	 * @return true if the idAddress is a valid IPv4 address, else false.
	 */
	public static boolean isValidIpV4Address(String ipAddress) {
		if (ipAddress == null || ipAddress.isEmpty()) {
			return false;
		}

		final int addressLength = ipAddress.length();

		// min: 0.0.0.0 and max: 255.255.255.255
		if (addressLength > 15 || addressLength < 7) {
			return false;
		}

		// Should have exactly 4 splits by .
		final String[] splits = ipAddress.split("\\.");
		if (splits.length != 4) {
			return false;
		}

		return isValidIPv4Word(splits[0]) && 
				isValidIPv4Word(splits[1])&& 
				isValidIPv4Word(splits[2])&& 
				isValidIPv4Word(splits[3]);
	}

	private static boolean isValidIPv4Word(final String word) {
		try {
			final int val = Integer.valueOf(word);
			return (val >= 0 && val <= 255);
		}catch(Exception e) {
			return false;
		}
		
	}

	public static void main(String[] args) {
		final String addr1 = "1.2.3.4";
		final String addr2 = "256.2.3.4";
		final String addr3 = "aa.aa.aa.aa";
		
		System.out.println("is '" + addr1 + "' valid IPv4 address ? " + isValidIpV4Address(addr1));
		System.out.println("is '" + addr2 + "' valid IPv4 address ? " + isValidIpV4Address(addr2));
		System.out.println("is '" + addr3 + "' valid IPv4 address ? " + isValidIpV4Address(addr3));
	}

}

Output

is '1.2.3.4' valid IPv4 address ? true
is '256.2.3.4' valid IPv4 address ? false
is 'aa.aa.aa.aa' valid IPv4 address ? false




 

 

 

Previous                                                 Next                                                 Home

No comments:

Post a Comment