Skip to content
This repository has been archived by the owner on Jul 1, 2022. It is now read-only.

Fix conversion of ip address to int #199

Merged
merged 2 commits into from
Jun 20, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion jaeger-core/src/main/java/com/uber/jaeger/utils/Utils.java
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ public static int ipToInt(String ip) throws EmptyIpException, NotFourOctetsExcep

int intIp = 0;
for (byte octet : octets.getAddress()) {
intIp = (intIp << 8) | (octet);
intIp = (intIp << 8) | (octet & 0xFF);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

for my education, since octet is already of type byte, why does & 0xFF make a difference?

Copy link
Contributor Author

@mabn mabn Jun 20, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

octet is promoted to integer via binary numeric promotion (https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.6.2), but it's a signed integer so the mask is filled with 1s on the left for negative numbers. & 0xFF converts it to unsigned (It's a byte so no need to care about int overflow. If it mattered then it should be 0xFFL). At least that's how I understand that.

In Java 8 that would instead be: Byte.toUnsignedInt(octet)

}
return intIp;
}
Expand Down
23 changes: 19 additions & 4 deletions jaeger-core/src/test/java/com/uber/jaeger/UtilsTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,9 @@

package com.uber.jaeger;

import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;

import com.uber.jaeger.exceptions.EmptyIpException;
import com.uber.jaeger.exceptions.NotFourOctetsException;
Expand All @@ -49,9 +51,22 @@ public void testIpToInt32EmptyIpException() {
}

@Test
public void testIpToInt32() {
int expectedIp = (127 << 24) | 1;
int actualIp = Utils.ipToInt("127.0.0.1");
assertEquals(expectedIp, actualIp);
public void testIpToInt32_localhost() {
assertThat(Utils.ipToInt("127.0.0.1"), equalTo((127 << 24) | 1));
}

@Test
public void testIpToInt32_above127() {
assertThat(Utils.ipToInt("10.137.1.2"), equalTo((10 << 24) | (137 << 16) | (1 << 8) | 2));
}

@Test
public void testIpToInt32_zeros() {
assertThat(Utils.ipToInt("0.0.0.0"), equalTo(0));
}

@Test
public void testIpToInt32_broadcast() {
assertThat(Utils.ipToInt("255.255.255.255"), equalTo(-1));
}
}