JAVA从url中分离ip和port
Posted 烟尘
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JAVA从url中分离ip和port相关的知识,希望对你有一定的参考价值。
public class NetAddrUtil {
/**
* 从url中分析出hostIP<br/>
* @param url
* @author wull
* @return
*/
public static String getIpFromUrl(String url) {
// 1.判断是否为空
if (url == null || url.trim().equals("")) {
return "";
}
// 2. 如果是以localhost,那么替换成127.0.0.1
if(url.startsWith("http://" + C.Net.LOCALHOST_STR) ){
url = url.replace("http://" + C.Net.LOCALHOST_STR, "http://" + C.Net.LOCALHOST_NUM) ;
}
String host = "";
Pattern p = Pattern.compile("(?<=//|)((\\w)+\\.)+\\w+");
Matcher matcher = p.matcher(url);
if (matcher.find()) {
host = matcher.group();
}
return host;
}
/**
* 从url中分析出hostIP:PORT<br/>
* @param url
* @author wull */
public static IpPortAddr getIpPortFromUrl(String url) {
// 1.判断是否为空
if (url == null || url.trim().equals("")) {
return null;
}
// 2. 如果是以localhost,那么替换成127.0.0.1
if(url.startsWith("http://" + C.Net.LOCALHOST_STR) ){
url = url.replace("http://" + C.Net.LOCALHOST_STR, "http://" + C.Net.LOCALHOST_NUM) ;
}
String host = "";
Pattern p = Pattern.compile("(?<=//|)((\\w)+\\.)+\\w+(:\\d{0,5})?");
Matcher matcher = p.matcher(url);
if (matcher.find()) {
host = matcher.group() ;
}
// 如果
if(host.contains(":") == false){
return new IpPortAddr(host, 80 );
}
String[] ipPortArr = host.split(":");
return new IpPortAddr(ipPortArr[0] , ConfigUtil.parseInt( ipPortArr[1] ));
}
public static void main(String [] args){
String url = "http://10.33.32.81:8080/login.action";
System.out.println(NetAddrUtil.getIpFromUrl(url) );
IpPortAddr addr= NetAddrUtil.getIpPortFromUrl(url) ;
System.out.println(addr.getIp() +"=========>" +addr.getPort() );
}
}
以上是关于JAVA从url中分离ip和port的主要内容,如果未能解决你的问题,请参考以下文章