Skip to content

Commit 697a657

Browse files
committed
bug fix: str2Ip value is not correct under some ips
1 parent 2b8464a commit 697a657

2 files changed

Lines changed: 11 additions & 10 deletions

File tree

IP.java

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import java.io.File;
22
import java.io.FileInputStream;
33
import java.io.IOException;
4-
import java.net.UnknownHostException;
54
import java.nio.ByteBuffer;
65
import java.nio.ByteOrder;
76
import java.util.Arrays;
@@ -188,15 +187,13 @@ private static long bytesToLong(byte a, byte b, byte c, byte d) {
188187
}
189188

190189
private static int str2Ip(String ip) {
191-
try {
192-
byte[] bytes = java.net.InetAddress.getByName(ip).getAddress();
193-
194-
return ((bytes[0] & 0xFF) << 24) |
195-
((bytes[1] & 0xFF) << 16) |
196-
((bytes[2] & 0xFF) << 8) |
197-
bytes[3];
198-
} catch (UnknownHostException e) {}
199-
return 0;
190+
String[] ss = ip.split("\\.");
191+
int a, b, c, d;
192+
a = Integer.parseInt(ss[0]);
193+
b = Integer.parseInt(ss[1]);
194+
c = Integer.parseInt(ss[2]);
195+
d = Integer.parseInt(ss[3]);
196+
return (a << 24) | (b << 16) | (c << 8) | d;
200197
}
201198

202199
private static long ip2long(String ip) {

TestMain.java

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,10 @@ public static void main(String[] args){
2222
for(int i=0; i<testSize; i++){
2323
ips[i] = IP.randomIp();
2424
}
25+
ips[0] = "119.147.158.186";
26+
ips[1] = "223.136.200.228";
27+
ips[2] = "68.104.105.223";
28+
ips[3] = "1.64.29.228";
2529
System.out.println("ip random completed");
2630

2731

0 commit comments

Comments
 (0)