IPv4比较
//比较两个ip的大小,如果大于,返回1,等于返回0,小于返回-1
{
var temp1;
var temp2;
temp1 = ipBegin.split(".");
temp2 = ipEnd.split(".");
for (var i = 0; i < 4; i++)
{
if (temp1[i]>temp2[i])
{
return 1;
}
else if (temp1[i]<temp2[i])
{
return -1;
}
}
return 0;
}
IPv6比较
public
class
Main {
public
static
void
main(String[] args) {
String str1 =
"3ffe:3201:1401::c8ff:fe4d:db39:5"
;
String str2 =
"3ffe:3201:1401::c8ff:fe4d:db39:9"
;
int
result = compare(str1, str2);
System.out.println(result);
}
/*
* 输入:两个表示ipv6地址的字符串
* 输出:1表示第一个地址大于第二个地址,0表示两个地址相同,-1表示小于
*/
public
static
int
compare(String ip1, String ip2) {
String[] ip1s = ip1.split(
":"
);
String[] ip2s = ip2.split(
":"
);
//循环比较对应的项
for
(
int
i =
0
; i < ip1s.length; i++) {
if
(ip1s[i].equals(
""
)) {
if
(ip2s[i].equals(
""
)) {
//对应的项都位空,往下比较
continue
;
}
else
{
return
-
1
;
}
}
else
{
if
(ip2s[i].equals(
""
)) {
return
1
;
}
else
{
//确定对应的项不位空,讲字符串转换位整数进行比较
int
value1 = Integer.parseInt(ip1s[i],
16
);
int
value2 = Integer.parseInt(ip2s[i],
16
);
if
(value1 > value2) {
return
1
;
}
else
if
(value1 < value2) {
return
-
1
;
}
else
{
continue
;
}
}
}
}
//循环结束,表示两个串表示的地址相同
return
0
;
}
}