import java.util.regex.Pattern; /** * Program to find whether given ip is IPv4 or IPv6 address * * @author sahir maredia (Kotia Solutions) * */ public class IPType { private static final String IPv4 = "(([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.){3}([01]?\\d\\d?|2[0-4]\\d|25[0-5])"; private static final String IPv6 = "([0-9a-f]{1,4}:){7}([0-9a-f]){1,4}"; /** * @param args */ public static void main(String[] args) { if (args.length != 1) { System.out.println("Please provide IP address as argument"); return; } String ipaddress = args[0]; Pattern ipv4 = Pattern.compile(IPv4); Pattern ipv6 = Pattern.compile(IPv6); if (ipv4.matcher(ipaddress).matches()) { System.out.println("Given IP Address : " + ipaddress + " is IPv4"); return; } else if (ipv6.matcher(ipaddress).matches()) { System.out.println("Given IP Address : " + ipaddress + " is IPv6"); return; } else { System.out.println("Given string is an invalid IP address"); } } }
Run this program as follows :
sahir@sahir-laptop:~/networklab$ javac IPType.java
sahir@sahir-laptop:~/networklab$ java IPType 192.168.1.1
Given IP Address : 192.168.1.1 is IPv4
sahir@sahir-laptop:~/networklab$ java IPType 0000:ffff:1234:4567:0000:4321:4567:ffff
Given IP Address : 0000:ffff:1234:4567:0000:4321:4567:ffff is IPv6
sahir@sahir-laptop:~/networklab$
sahir@sahir-laptop:~/networklab$ java IPType 192.168.1.1
Given IP Address : 192.168.1.1 is IPv4
sahir@sahir-laptop:~/networklab$ java IPType 0000:ffff:1234:4567:0000:4321:4567:ffff
Given IP Address : 0000:ffff:1234:4567:0000:4321:4567:ffff is IPv6
sahir@sahir-laptop:~/networklab$
No comments:
Post a Comment