Created
October 23, 2017 21:50
-
-
Save lupsyn/b3d3e17a6f0ba1d462a7acbd2594b4ce to your computer and use it in GitHub Desktop.
IpTransformationsHelper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* | |
* @author enricodelzotto | |
* @since 23/10/2017 | |
*/ | |
public class IpTransformationsHelper { | |
/** | |
* @param addr format xxx.xxx.xxx.xxx | |
* @param mask string rapresentation of an int | |
* @return | |
*/ | |
public static int convertIpToIntWithMask(String addr, String mask) { | |
byte[] ipByts = new byte[4]; | |
String[] parts = addr.split("\\."); | |
int ip = ((Integer.parseInt(parts[3]) << 24 | |
| Integer.parseInt(parts[2]) << 16 | |
| Integer.parseInt(parts[1]) << 8 | |
| Integer.parseInt(parts[1]) << 0)) & Integer.parseInt(mask, 16); | |
return ip; | |
} | |
public static int converIpToInt(String addr) { | |
String[] parts = addr.split("\\."); | |
int ip = ((Integer.parseInt(parts[3]) << 24 | |
| Integer.parseInt(parts[2]) << 16 | |
| Integer.parseInt(parts[1]) << 8 | |
| Integer.parseInt(parts[1]) << 0)); | |
return ip; | |
} | |
/** | |
* Return the String rapresentation of an inet IP from a integer | |
* | |
* @param i | |
* @return | |
*/ | |
public static String intToIp(int i) { | |
return ((i >> 24) & 0xFF) + "." + | |
((i >> 16) & 0xFF) + "." + | |
((i >> 8) & 0xFF) + "." + | |
(i & 0xFF); | |
} | |
/** | |
* Compare two different ip | |
* @param ipOne | |
* @param ipTwo | |
* @param mask | |
* @return | |
*/ | |
public static boolean areTheSameIpWithDifferentMask(String ipOne, String ipTwo, String mask) { | |
return converIpToInt(ipOne) == convertIpToIntWithMask(ipTwo, mask); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment