java IP轉換

來源:互聯網
上載者:User
  1. /**
     
  2.  * IP進位轉換工具
     
  3.  * 
     
  4.  * @author YM
     
  5.  */
      
  6. public
     
    class
     IpConvert {  
  7.   
  8.     /**
     
  9.      * 將
    IP進位(如:192.168.1.1)轉換成十進位(如:3232235777)
     
  10.      * 
     
  11.      * @param ip
     
  12.      * @return
     
  13.      */
      
  14.     public
     
    static
     
    long
     getIp10(String ip) {  
  15.         long
     ip10 = 
    0
    ;  
  16.         String[] ss = ip.trim().split("//."
    );  
  17.         for
     (
    int
     i = 
    0
    ; i < 
    4
    ; i++) {  
  18.             ip10 += Math.pow(256

    3
     - i) * Integer.parseInt(ss[i]);  
  19.         }  
  20.   
  21.         return
     ip10;  
  22.     }  
  23.   
  24.     /**
     
  25.      * 將
    十進位(如:3232235777)IP轉換成IP進位(如:192.168.1.1)
     
  26.      * 
     
  27.      * @param ip10
     
  28.      * @return
     
  29.      */
      
  30.     public
     
    static
     String getIp(
    long
     ip10) {  
  31.         String ip = ""
    ;  
  32.         long
     temp = 
    0
    ;  
  33.   
  34.         for
     (
    int
     i = 
    3
    ; i >= 
    0
    ; i--) {  
  35.             temp = ip10 / (long
    ) Math.pow(
    256
    , i) % 
    256
    ;  
  36.             if
     (i == 
    3
    ) {  
  37.                 ip = ip + temp;  
  38.             } else
     {  
  39.                 ip = ip + "."
     + temp;  
  40.             }  
  41.         }  
  42.   
  43.         return
     ip;  
  44.     }  
  45.   
  46.     public
     
    static
     
    void
     main(String[] args) {  
  47.         System.out.println(getIp10("192.168.1.1"
    ));  
  48.         System.out.println(getIp(getIp10("192.168.1.1"
    )));  
  49.     }  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.