在TCP/IP 在互联网上,经常需要查询主机的IP地址和www服务器的IP地址。虽然我们可以使用IPCONFIG 和PING 查询IP地址,但如果在应用程序或APPLET中使用此命令,则会损坏我们的应用程序界面。 为此,我用JAVA 可以直接查询自己主机的IP地址和www服务器的IP地址,做一个简单的程序。
// 文件名为 NetTool.java (注:JAVA 语言中大小写敏感)import java.net.*;public class NetTool{InetAddress myIPaddress=null;InetAddress myServer=null;
public static void main( String args[]){
NetTool mytool;mytool=new NetTool();
System.out.println("Your host IP is: "+ mytool.getMyIP());System.out.println("The Server IP is :"+mytool.getServerIP());
}
//获取LOCALHOSTIP地址public InetAddress getMyIP() {try { myIPaddress=InetAddress.getLocalHost();}catch (UnknownHostException e) {}return (myIPaddress);}//取得 www.abc.com PublicicIP地址 InetAddress getServerIP(){try {myServer=InetAddress.getByName("www.abc.com");}catch (UnknownHostException e) {}return (myServer);}
} 由于JAVA语言的跨平台特性,上述程序可以在任何装有JVM系统的机器上直接编译。上述程序旨在吸引玉石。读者可以将上述代码转换为APPLET,添加到您的homepage中,或将地址查询结果写入文件中,建立自己的本地hosts文件
