zoukankan      html  css  js  c++  java
  • 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() );
    }
    }

  • 相关阅读:
    SQL Server数据库开发基础
    C#面向对象的概念 ----继承,里氏转换和几种集合(2)
    C#面向对象的概念 ----继承,里氏转换和几种集合(1)
    C#面向对象的概念
    C#的引用类型及stringbuilder类(增补)
    C#方法构建的简单介绍
    C#的结构和数组
    C#debug技巧和反编译器
    C#的语法----程序结构(6)
    C#的语法----程序结构(5)
  • 原文地址:https://www.cnblogs.com/histlyb/p/7047899.html
Copyright © 2011-2022 走看看