sap*_*Pro 1 java networking ping unknown-host
我写了下面的代码来试试ping
.但是当我运行它时,会抛出以下异常:
java.net.UnknownHostException: http://localhost:8084/server/index.jsp
at java.net.Inet6AddressImpl.lookupAllHostAddr(Native Method)
at java.net.InetAddress$1.lookupAllHostAddr(Unknown Source)
at java.net.InetAddress.getAddressFromNameService(Unknown Source)
at java.net.InetAddress.getAllByName0(Unknown Source)
at java.net.InetAddress.getAllByName0(Unknown Source)
at java.net.InetAddress.getAllByName(Unknown Source)
at java.net.InetAddress.getByName(Unknown Source)
at Tester.main(Tester.java:10)
Run Code Online (Sandbox Code Playgroud)
import java.net.InetAddress;
class Tester {
public static void main(String args[]) {
try {
InetAddress address = InetAddress.getByName("http://localhost:8084/server/index.jsp");
boolean isReachable = address.isReachable(2000);
if(isReachable)
System.out.println("The address is reachable");
else
System.out.println("The address is not reachable");
} catch(Exception exc) {
exc.printStackTrace();
}
}
}
Run Code Online (Sandbox Code Playgroud)
为什么会这样?服务器正在运行,页面在Web浏览器中正常打开.
问题出在这一行:
InetAddress address = InetAddress.getByName(
"http://localhost:8084/server/index.jsp");
Run Code Online (Sandbox Code Playgroud)
该InetAddress.getByName(String)
方法需要主机名.你给它一个URL字符串.该地址的主机名组件是"localhost"
.
如果要"ping"与URL关联的主机,则需要解析URL并提取主机名组件,如下所示:
String hostname = new URL(str).getHost();
Run Code Online (Sandbox Code Playgroud)
但是,您需要处理URL格式错误的情况,或者没有主机名组件的情况.
我想你实际上是在尝试测试其他主机名,因为发送ICMP_PING请求"localhost"
(通常127.0.0.1
)是没有意义的.
归档时间: |
|
查看次数: |
1830 次 |
最近记录: |