Skip to content
Snippets Groups Projects
Commit 76671f15 authored by Alex Reimers's avatar Alex Reimers
Browse files

IPv4.java - Add static method for IPv4 from int to byte[].

parent 0f825d26
No related branches found
No related tags found
No related merge requests found
......@@ -456,9 +456,9 @@ public class IPv4 extends BasePacket {
/**
* Accepts an IPv4 address of the form xxx.xxx.xxx.xxx, ie 192.168.0.1 and
* returns the corresponding byte array
* @param ipAddress
* @return
* returns the corresponding byte array.
* @param ipAddress The IP address in the form xx.xxx.xxx.xxx.
* @return The IP address separated into bytes
*/
public static byte[] toIPv4AddressBytes(String ipAddress) {
String[] octets = ipAddress.split("\\.");
......@@ -472,6 +472,20 @@ public class IPv4 extends BasePacket {
}
return result;
}
/**
* Accepts an IPv4 address in the form of an integer and
* returns the corresponding byte array.
* @param ipAddress The IP address as an integer.
* @return The IP address separated into bytes.
*/
public static byte[] toIPv4AddressBytes(int ipAddress) {
return new byte[] {
(byte)(ipAddress >>> 24),
(byte)(ipAddress >>> 16),
(byte)(ipAddress >>> 8),
(byte)ipAddress};
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
......
......@@ -35,8 +35,13 @@ import org.junit.Test;
public class IPv4Test {
@Test
public void testToIPv4Address() {
int expected = 0xc0a80001;
assertEquals(expected, IPv4.toIPv4Address("192.168.0.1"));
int intIp = 0xc0a80001;
String stringIp = "192.168.0.1";
byte[] byteIp = new byte[] {(byte)192, (byte)168, (byte)0, (byte)1};
assertEquals(intIp, IPv4.toIPv4Address(stringIp));
assertEquals(intIp, IPv4.toIPv4Address(byteIp));
assertTrue(Arrays.equals(byteIp, IPv4.toIPv4AddressBytes(intIp)));
assertTrue(Arrays.equals(byteIp, IPv4.toIPv4AddressBytes(stringIp)));
}
@Test
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment