InetAddress.toString() returns a forward slash

后端 未结 2 731
情话喂你
情话喂你 2021-02-18 19:46

I have a variable packet of type DatagramPacket. While packet.getAddress().toString() results in a String representing an the IP address, it has an ext

2条回答
  •  南旧
    南旧 (楼主)
    2021-02-18 20:18

    If you just want the IP, use the host address:

    String address = InetAddress.getByName("stackoverflow.com").getHostAddress();
    

    If you just want the host name, use

    String hostname = InetAddress.getByName("stackoverflow.com").getHostName();
    

    The slash you're seeing is probably when you do an implicit toString() on the returned InetAddress as you try to print it out, which prints the host name and address delimited by a slash (e.g. stackoverflow.com/64.34.119.12). You could use

    String address = InetAddress.getByName("stackoverflow.com").toString().split("/")[1];
    String hostname = InetAddress.getByName("stackoverflow.com").toString().split("/")[0];
    

    But there is no reason at all to go to a String intermediary here. InetAddress keeps the two fields separate intrinsically.

提交回复
热议问题