@SpringBootTest(classes = ServeApplication.class, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class IpTest {
/**
* @Description: 判断多个IP地址的合法性,这里采用了正则表达式的方法来判断(多个IP之间用 "," 分隔)
* @param: [ips 多个ip]
* @return:boolean
*/
public boolean ipsCheck(String ips) {
boolean result = true;
if (ips != null && !ips.isEmpty()) {
// 定义正则表达式
String regex = "^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\." +
"(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\." +
"(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\." +
"(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$";
String[] list = ips.split(",");
for (String s : list) {
boolean legitimate = s.matches(regex);
if (!legitimate) {
result = false;
break;
}
}
} else {
result = false;
}
return result;
}
@Test
public void ipTests() {
String str = "8.8.8.8,4.4.4.4";
System.out.println("str:" + this.ipsCheck(str));
String str1 = "8.88.8,4.4.4.4";
System.out.println("str1:" + this.ipsCheck(str1));
String str2 = "8.8.8.84.4.4.4";
System.out.println("str2:" + this.ipsCheck(str2));
String str3 = "";
System.out.println("str3:" + this.ipsCheck(str3));
String str4 = null;
System.out.println("str4:" + this.ipsCheck(str4));
String str5 = " ";
System.out.println("str5:" + this.ipsCheck(str5));
if (this.ipsCheck(str1)){
System.out.println("1");
}else {
System.out.println("2");
}
}
}