2011-11-11 90 views
0

我下面condtion检查的帮助下,IP是否可达与否IP地址检查了错误

if (InetAddress.getByName(server1IPAddress).isReachable(1000) == false) 
{   
    ...... 
    ...... 
} 

及其与普通IP地址192.168.1.158 正常工作,但是当我包括端口号以及外部IP 61.17.172.4:85它显示一个错误UnknownHostException

将任何一个可以帮助我请

+0

如果您删除端口号并仅传递IP地址,会发生什么情况?像61.17.172.4 .. – user370305

+0

使用InetSocketAddress sockaddr = new InetSocketAddress(ipAddress,portNo); – user370305

回答

0

我认为这是正常工作。指定这种方式的端口对于诸如http和URL之类的协议是正确的,但不适用于主机地址。我认为你需要剥离端口部分来调用getByName。

如果你有一个像http://host.com:85/foo/bar.html一个完整的URL,你可以使用类似下面得到一个主机地址:

public static String extractAddressFromUrl(String url) { 
     String urlToProcess = null; 

     //find protocol 
     int protocolEndIndex = url.indexOf("://"); 
     if(protocolEndIndex>0) { 
      urlToProcess = url.substring(protocolEndIndex + 3); 
     } else { 
      urlToProcess = url; 
     } 

     // If we have port number in the address we strip everything 
     // after the port number 
     int pos = urlToProcess.indexOf(':'); 
     if (pos >= 0) { 
      urlToProcess = urlToProcess.substring(0, pos); 
     } 

     // If we have resource location in the address then we strip 
     // everything after the '/' 
     pos = urlToProcess.indexOf('/'); 
     if (pos >= 0) { 
      urlToProcess = urlToProcess.substring(0, pos); 
     } 

     // If we have ? in the address then we strip 
     // everything after the '?' 
     pos = urlToProcess.indexOf('?'); 
     if (pos >= 0) { 
      urlToProcess = urlToProcess.substring(0, pos); 
     } 
     return urlToProcess; 
    } 

而且,如果youre设法找出一个主机可用您可以考虑使用ConnectivityManager.requestRouteToHost()

0

您不能使用mmeyer建议的方法将输入字符串拆分为IP和端口,然后使用新的InetAddress方法?一个未经测试的例子是...

String urlToProcess = null; /* your input string */ 

int pos = urlToProcess.indexOf(':'); /* find the : */ 
if (pos >= 0) { 
    ipAddress = urlToProcess.substring(0,pos); /* return ip without the port */ 
    portNo = urlToProcess.substring(pos + 1); /* return the port */ 
} 

sockaddr = new InetSocketAddress(ipAddress, portNo); 

if (InetAddress.getByName(sockaddr).isReachable(1000) == false) { 
...your code.... 
} 

就像我说的,我不是专家,我没有检查代码,以便把它与少许盐。它只是每个人的答案的组合。