Android:需要帮助从主机名获取IP地址

时间:2014-04-01 09:35:57

标签: android network-programming

我在我的活动及其工作中使用以下工具。但我得到的输出(主机名)不是我想要的方式。例如,如果我需要找到谷歌的IP,我得到它像www.google.com/74.125.224.72

应该就像74.125.224.72

一样

我是Android新手,请帮帮我。这是我的代码:

String host = editText1.getText().toString();
try {
    InetAddress[] hostInetAddress = InetAddress.getAllByName(host);
    String all = "";
    for(int i = 0; i < hostInetAddress.length; i++){
        all = all + hostInetAddress[i].toString() + "\n";
    }
    textInetAddress.setText(all);
}

3 个答案:

答案 0 :(得分:1)

使用以下命令获取您的姓名/ ip_address:

InetAddress address = InetAddress.getByName(new URL(urlString).getHost());
//it will fetch name/ip_address (eg. www.google.com/74.125.224.72) of the url you enter

然后使用:

获取ip_address
String ip = address.getHostAddress();
//it will fetch only ip_address (eg. "74.125.224.72" ) from the abouve url

所以而不是

 for(int i = 0; i < hostInetAddress.length; i++){
                    all = all + hostInetAddress[i].toString() + "\n";
                }

使用以下代码

 for(int i = 0; i < hostInetAddress.length; i++){
                    all = all + hostInetAddress[i].getHostAddress().toString() + "\n";
                }

答案 1 :(得分:0)

试试这个:

String[] ip = all.split("/");
textInetAddress.setText(ip[1]);

答案 2 :(得分:0)

无需循环。这样可行。
    hostInetAddress [0] .getHostAddress();