用Java编程获得本机和服务器IP地址

  在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());
  }
  //取得LOCALHOST的IP地址
  public InetAddress getMyIP(){
  try{myIPaddress=InetAddress.getLocalHost();}
  catch(UnknownHostException e){}
  return(myIPaddress);
  }
  //取得www.abc.com的IP地址
  public InetAddress getServerIP(){
  try{myServer=InetAddress.getByName("www.abc.com");}
  catch(UnknownHostException e){}
  return(myServer);
  }
  }