Skip to content

Commit 19e79dc

Browse files
committed
Fixed bug when there is no search tree
1 parent 0e6c3c6 commit 19e79dc

2 files changed

Lines changed: 14 additions & 13 deletions

File tree

src/main/java/com/maxmind/maxminddb/MaxMindDbReader.java

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -94,12 +94,13 @@ private int findAddressInTree(InetAddress address)
9494
throws InvalidDatabaseException {
9595
byte[] rawAddress = address.getAddress();
9696

97-
int nodeNum = this.startNode(rawAddress.length * 8);
97+
int bitLength = rawAddress.length * 8;
98+
int record = this.startNode(bitLength);
9899

99-
for (int i = 0; i < rawAddress.length * 8; i++) {
100+
for (int i = 0; i < bitLength; i++) {
100101
int b = 0xFF & rawAddress[i / 8];
101102
int bit = 1 & (b >> 7 - (i % 8));
102-
int record = this.readNode(nodeNum, bit);
103+
record = this.readNode(record, bit);
103104

104105
if (record == this.metadata.nodeCount) {
105106
// record is empty
@@ -108,16 +109,14 @@ int record = this.readNode(nodeNum, bit);
108109
// record is a data pointer
109110
return record;
110111
}
111-
112-
nodeNum = record;
113112
}
114113
throw new InvalidDatabaseException("Something bad happened");
115114
}
116115

117-
private int startNode(int length) throws InvalidDatabaseException {
116+
private int startNode(int bitLength) throws InvalidDatabaseException {
118117
// Check if we are looking up an IPv4 address in an IPv6 tree. If this
119118
// is the case, we can skip over the first 96 nodes.
120-
if (this.metadata.ipVersion == 6 && length == 32) {
119+
if (this.metadata.ipVersion == 6 && bitLength == 32) {
121120
return this.ipV4StartNode();
122121
}
123122
// The first node of the tree is always node 0, at the beginning of the
@@ -135,12 +134,14 @@ private int ipV4StartNode() throws InvalidDatabaseException {
135134
if (this.ipV4Start != 0) {
136135
return this.ipV4Start;
137136
}
138-
int nodeNum = 0;
139-
for (int i = 0; i < 96; i++) {
140-
nodeNum = this.readNode(nodeNum, 0);
137+
int node = 0;
138+
int nextNode = 0;
139+
for (int i = 0; i < 96 && nextNode < this.metadata.nodeCount; i++) {
140+
node = nextNode;
141+
nextNode = this.readNode(node, 0);
141142
}
142-
this.ipV4Start = nodeNum;
143-
return nodeNum;
143+
this.ipV4Start = node;
144+
return node;
144145
}
145146

146147
private int readNode(int nodeNumber, int index)

src/test/java/com/maxmind/maxminddb/ReaderTest.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ public void testNoIpV4SearchTree() throws IOException, URISyntaxException {
5151

5252
MaxMindDbReader reader = new MaxMindDbReader(new File(file));
5353

54-
assertEquals("::/64", reader.get(InetAddress.getByName("::1:1.1.1.1"))
54+
assertEquals("::/64", reader.get(InetAddress.getByName("1.1.1.1"))
5555
.textValue());
5656
}
5757

0 commit comments

Comments
 (0)