2011-06-14 49 views

回答

5

顯然你不能在一個整數

實際存儲的IP地址,這是所有的IP(V4)地址是 - 一個32位整數(在IPv6的情況下是128位)。

你正在談論的「人類可讀」格式是通過將整數位分成8個稱爲「八位位組」的字符串並轉換爲基數10來產生的。 「192.168.0.1」。

該地址的比特將是如下(添加的可讀性空格):

11000000 10101000 00000000 00000001 

其對應於十進制整數3232235521。

+0

謝謝,我顯然也習慣了人類可讀的格式;-) – 2011-06-14 15:06:10

8

你其實可以。

作爲int的IP地址是:AABBCCDD並且以人類可讀的形式,它是AA.BB.CC.DD但是以十進制爲基礎。正如你所看到的,你可以使用按位操作或將int轉換爲字節數組輕鬆地提取它們。

看到的畫面:

enter image description here

+0

真棒圖解說明這一點,謝謝!只是希望,它會包含在android文檔中。 – 2011-06-14 15:05:51

5

正如其他海報所提到的,一個IP地址是可裝在一個INT 4個字節。安德烈給出了一個很好的例子,顯示瞭如何。如果將它存儲在InetAddress對象中,則可以使用ToString()獲取人類可讀版本。喜歡的東西:

byte[] bytes = BigInteger.valueOf(ipAddress).toByteArray(); 
InetAddress address = InetAddress.getByAddress(bytes); 
String s = address.ToString(); 
+2

不幸的是,IP地址的順序錯誤,例如192.168.101.102將輸出爲102.101.168.192。至少使用WifiInfo.getIPAddress()。反過來使用(通過)Ace的字節轉換。 – 2013-11-06 13:32:46

7

使用此功能 NetworkUtils.java \構架\基地\核心\ java的\機器人\ NET)

public static InetAddress intToInetAddress(int hostAddress) { 
    byte[] addressBytes = { (byte)(0xff & hostAddress), 
          (byte)(0xff & (hostAddress >> 8)), 
          (byte)(0xff & (hostAddress >> 16)), 
          (byte)(0xff & (hostAddress >> 24)) }; 

    try { 
     return InetAddress.getByAddress(addressBytes); 
    } catch (UnknownHostException e) { 
     throw new AssertionError(); 
    } 
} 
0

只是反向您以字節爲單位收到ip地址

byte[] bytes = BigInteger.valueOf(ipAddress).toByteArray(); 
ArrayUtils.reverse(bytes); 
// then 
InetAddress myaddr = InetAddress.getByAddress(ipAddress); 
String ipString = myaddr.getHostAddress();