Home  >  Article  >  Java  >  How to determine whether ip is legal in java

How to determine whether ip is legal in java

尚
Original
2019-12-30 15:27:164807browse

How to determine whether ip is legal in java

java判断IP地址是否合法的方法:(推荐:java视频教程

/**
	 * 判断IP地址的合法性,这里采用了正则表达式的方法来判断 return true,合法
	 */
	public static boolean ipCheck(String text) {
		if (text != null && !text.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)$";
			// 判断ip地址是否与正则表达式匹配
			if (text.matches(regex)) {
				// 返回判断信息
				return true;
			} else {
				// 返回判断信息
				return false;
			}
		}
		return false;
	}

matches() 方法用于检测字符串是否匹配给定的正则表达式。

调用

public static void main(String[] args) {
		String b = "191.168.32.1";
		if (!Tool.ipCheck(b)) {
			System.out.println("错误");
		}else {
			System.out.println("正确");
		}
	}

更多java知识请关注java基础教程栏目。

The above is the detailed content of How to determine whether ip is legal in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn