2012-02-18 159 views
9

我已經搜索了很多,但我找不到任何方式將inetaddress類型轉換爲字符串(可能是我的搜索不是很好:S)。我必須將其轉換爲字符串類型,因爲我必須在textarea(gui組件)中顯示需要字符串類型的結果。所以任何人都可能如何?Java:inetaddress轉換爲字符串

回答

19

InetAddress類的Java API有很好的方法滿足您的需求,我明白了。 試試這些方法。您可以查看InetAddress的其他屬性獲取方以瞭解您的進一步要求。

public static void main (String [] args) throws UnknownHostException 
{ 
    // Instantiate your own InetAddress object. 
    InetAddress address = InetAddress.getLocalHost(); 
    String hostIP = address.getHostAddress() ; 
    String hostName = address.getHostName(); 
    System.out.println("IP: " + hostIP + "\n" + "Name: " + hostName); 
} 
5

您是否試過InetAddress.toString()方法?

+0

這將返回一個正斜槓。改用getHostAddress()。請參閱http://stackoverflow.com/questions/12947435/inetaddress-tostring-returns-a-forward-slash – LeslieM 2016-12-05 14:12:15

1

什麼

System.out.println(Inet4Address.getLocalHost().getHostAddress()); 

3

只需調用InetAddress toString()方法即可。另外,如果您特別需要主機名,請使用getHostName。如果您想要IP地址的字符串表示形式,請使用getHostAddress()

樣本:

InetAddress inet = InetAddress.getByName("193.125.22.1"); 
System.out.println(inet.toString()); 

更多信息,請參見:http://www.java2s.com/Code/JavaAPI/javax.net/InetAddressgetByNameStringname.htm

+0

upvoted for the important bit:getHostAddress if you just want the address string – 2014-09-06 18:36:08