How to validate an IP address in Java?

by katharina , in category: Java , a year ago

How to validate an IP address in Java?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by elnora , a year ago

@katharina To validate an IP address in Java, you can use the InetAddress#getByName method and check if the returned object is an instance of InetAddress. Here's an example:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
import java.net.InetAddress;
import java.net.UnknownHostException;

public class Main {
    public static void main(String[] args) throws UnknownHostException {
        // IP address to validate
        String ip = "192.168.0.1";

        // Use the InetAddress#getByName method to check if the IP address is valid
        InetAddress address = InetAddress.getByName(ip);

        // Check if the address is an instance of InetAddress
        if (address != null) {
            System.out.println("Valid IP address");
        } else {
            System.out.println("Invalid IP address");
        }
        // Output: Valid IP address
    }
}


by jerod.sauer , 4 months ago

@katharina 

The code provided above only checks if the syntax of the IP address is valid. To perform a more comprehensive validation, you can use a regular expression pattern. Here's an updated example that uses regular expressions to validate an IP address in Java:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    public static void main(String[] args) {
        // IP address to validate
        String ip = "192.168.0.1";

        // Regular expression pattern for IP address validation
        String pattern = "^([01]?\d\d?|2[0-4]\d|25[0-5])\." +
                        "([01]?\d\d?|2[0-4]\d|25[0-5])\." +
                        "([01]?\d\d?|2[0-4]\d|25[0-5])\." +
                        "([01]?\d\d?|2[0-4]\d|25[0-5])$";

        // Create a Pattern object with the regex pattern
        Pattern p = Pattern.compile(pattern);

        // Create a Matcher object to match the pattern against the IP address
        Matcher m = p.matcher(ip);

        // Check if the IP address matches the regex pattern
        if (m.matches()) {
            System.out.println("Valid IP address");
        } else {
            System.out.println("Invalid IP address");
        }
        // Output: Valid IP address
    }
}


In this example, the regular expression pattern ^([01]?dd?|2[0-4]d|25[0-5]). ([01]?dd?|2[0-4]d|25[0-5]). ([01]?dd?|2[0-4]d|25[0-5]). ([01]?dd?|2[0-4]d|25[0-5])$ is used to validate the IP address. This pattern checks for numbers in the range of 0-255 separated by dots. If the IP address matches this pattern, it is considered valid.