简体   繁体   中英

Java:inetaddress to String conversion

我搜索了很多,但我找不到任何方法将inetaddress类型转换为字符串(可能是我的搜索不是那么好:S)。我必须将其转换为字符串类型,因为我必须在textarea中显示结果(gui组件)需要字符串类型。任何人都可以这样做?

Java API for InetAddress class has good methods for your needs, I see. Try these methods. You can check out other property getters of InetAddress for your further requirements.

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);
}

你试过InetAddress.toString()方法吗?

Just call the InetAddress toString() method. Also, if you specifically want the host name, use getHostName. If you want a string representation of the IP address, use getHostAddress() .

sample :

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

for more information see: http://www.java2s.com/Code/JavaAPI/javax.net/InetAddressgetByNameStringname.htm

What about

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

?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM