How to check if a string is IPv4 or IPv6 or invalid in Java

1 Answer

0 votes
import java.net.InetAddress;
import java.net.UnknownHostException;

public class Main {

    public static String checkIpAddress(String s) {
        try {
            InetAddress ip = InetAddress.getByName(s);

            if (ip.getHostAddress().contains(":")) {
                return "IPv6";
            } else {
                return "IPv4";
            }

        } catch (UnknownHostException e) {
            return "Invalid";
        }
    }

    public static void main(String[] args) {
        System.out.println(checkIpAddress("112.128.1.2"));
        System.out.println(checkIpAddress("2001:0dc7:85b2:0000:0000:6d3e:0380:8651"));
        System.out.println(checkIpAddress("999.999.999.999"));
        System.out.println(checkIpAddress("abc"));
    }
}


/*
run:

IPv4
IPv6
Invalid
Invalid

*/

 



answered Jan 19 by avibootz

Related questions

...