获取本机IP

package com.tianren.service;
import java.net.*;

import sun.security.krb5.internal.HostAddress;

public class Test{
InetAddress myIPaddress = null;
InetAddress myServer = null;
String hostAddress = null;
String hostName = null;
String Address = null ;
String Name = null ;
public static void main(String args[]) {

  Test mytool;
  mytool = new Test();
  mytool.getAllServerIP();
//  System.out.println("Your host IP is: " + mytool.getMyIP());
//  System.out.println("The Server IP is :" + mytool.getServerIP());
}

// 取得LOCALHOST的IP地址
public String getMyIP() {
  try {
   myIPaddress = InetAddress.getLocalHost();
   hostAddress = myIPaddress.getHostAddress();//仅仅获得IP地址
   hostName = myIPaddress.getHostName();//获得本地名称
  } catch (UnknownHostException e) {
  }
  return (hostName);
}

// 取得 www.abc.com 的IP地址
public String getServerIP() {
  try {
   myServer = InetAddress.getByName("www.abc.com");
   Address = myServer.getHostAddress();//获得www.abc.com的ip地址
   Name = myServer.getHostName();//获得域名
  } catch (UnknownHostException e) {
  }
  return (Name);
}
//获取此域名下的所有IP
public void getAllServerIP(){
  String name = "www.microsoft.com";
  try{
  
   InetAddress[] addresses= InetAddress.getAllByName(name);
   for(int i =0;i<addresses.length;i++){
    System.out.println(addresses[i].getHostAddress());
   }
  }catch(Exception e){
   System.err.println("Unable to find: "+name);

  }
}

}

你可能感兴趣的:(IP)