15

I have searched a lot but i could not find any way to convert inetaddress type to string(may be my searching is not that good :S).I have to convert it into string type because i have to display the result in textarea(gui component) which requires string type.So can anyone how is this possible??

Xara
  • 8,748
  • 16
  • 52
  • 82

4 Answers4

30

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);
}
Juvanis
  • 25,802
  • 5
  • 69
  • 87
9

Have you tried to InetAddress.toString() method?

Richard Walton
  • 4,789
  • 3
  • 38
  • 49
3

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

Sam
  • 6,770
  • 7
  • 50
  • 91
2

What about

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

?

lhlmgr
  • 2,087
  • 1
  • 22
  • 38