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??
Asked
Active
Viewed 3.8k times
4 Answers
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
-
4This returns a forward slash. Use getHostAddress() instead. See http://stackoverflow.com/questions/12947435/inetaddress-tostring-returns-a-forward-slash – LeslieM Dec 05 '16 at 14:12
-
this will return hostname/ipaddress. – Gowtham Jul 23 '20 at 04:04
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
-
upvoted for the important bit : getHostAddress if you just want the address string – Todd Freed Sep 06 '14 at 18:36
2
What about
System.out.println(Inet4Address.getLocalHost().getHostAddress());
?

lhlmgr
- 2,087
- 1
- 22
- 38