Xara
Xara

Reputation: 9108

Java:inetaddress to String conversion

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??

Upvotes: 15

Views: 40399

Answers (4)

Juvanis
Juvanis

Reputation: 25950

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

Upvotes: 30

Sam
Sam

Reputation: 6900

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

Upvotes: 3

lhlmgr
lhlmgr

Reputation: 2187

What about

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

?

Upvotes: 2

Richard Walton
Richard Walton

Reputation: 4785

Have you tried to InetAddress.toString() method?

Upvotes: 9

Related Questions