【问题标题】:Slash before InetAddress.getByName(host)InetAddress.getByName(host) 前的斜线
【发布时间】:2011-09-09 12:42:55
【问题描述】:

如何删除InetAddress.getbyName 输出中的斜线?


更新

谢谢大家,我刚刚做到了。

其中一个解决方案是:

String ip_old = myInetaddress.toString(); 
String ip_new = ip_old.substring(1); 

【问题讨论】:

  • 您现在使用的那个解决方案是一个糟糕的 hack。请使用 getHostAddress() 函数检索您想要的内容。

标签: java networking


【解决方案1】:

如果你只想要IP,使用主机地址:

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

如果您只想要主机名,请使用

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

编辑

您看到的斜线可能是当您尝试打印返回的InetAddress 时对返回的toString() 执行隐式toString(),这会打印由斜线分隔的主机名和地址(例如stackoverflow.com/64.34.119.12) .你可以使用

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

但是这里完全没有理由去String 中介。 InetAddress 使这两个字段在本质上是分开的。

【讨论】:

    【解决方案2】:

    我假设你在这之后做一个 toString ?为什么不直接使用普通的字符串操作,也就是子字符串?

    【讨论】:

    • 是的!刚刚做到了。谢谢!代码- String ip_old=myInetaddress.toString();字符串 ip_new=ip_old.substring(1);
    • @P Ramesh:这是一个非常糟糕的解决方案,因为您将无缘无故地访问 String 并返回。 InetAddress 已经在内部分别保留了主机名和地址,您只需要像我的回答一样向它询问地址即可。你能解释一下为什么你不想使用逻辑方式吗?
    猜你喜欢
    • 1970-01-01
    • 2014-12-07
    • 2016-09-03
    • 1970-01-01
    • 2016-05-26
    • 2010-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多