Bellow method is validating if string is correct IPv4 address it returns true if it is valid. Any improvements in regex and elegance would be very appreciated:
public static boolean validIP(String ip) { if (ip == null || ip.isEmpty()) return false; ip = ip.trim(); if ((ip.length() < 6) & (ip.length() > 15)) return false; try { Pattern pattern = Pattern.compile("^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$"); Matcher matcher = pattern.matcher(ip); return matcher.matches(); } catch (PatternSyntaxException ex) { return false; } }
In Java you can use the String. matches(String regex) method. With regexes we say you match a string against a pattern If a match is successful, . matches() returns true.
In Java, you can use InetAddress. getLocalHost() to get the Ip Address of the current Server running the Java app and InetAddress.
A valid IP address must be in the form of A.B.C.D, where A,B,C and D are numbers from 0-255. The numbers cannot be 0 prefixed unless they are 0. Note:You only need to implement the given function.
IPv4 is a version 4 of IP. It is a current version and the most commonly used IP address. It is a 32-bit address written in four numbers separated by 'dot', i.e., periods. This address is unique for each device. For example, 66.94.29.13.
Here is an easier-to-read, slightly less efficient, way you could go about it.
public static boolean validIP (String ip) { try { if ( ip == null || ip.isEmpty() ) { return false; } String[] parts = ip.split( "\\." ); if ( parts.length != 4 ) { return false; } for ( String s : parts ) { int i = Integer.parseInt( s ); if ( (i < 0) || (i > 255) ) { return false; } } if ( ip.endsWith(".") ) { return false; } return true; } catch (NumberFormatException nfe) { return false; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With