通過JAVA API顯示本機IP地址和網絡上任何一臺可以訪問到的服務器的IP地址
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class GetIP {
private InetAddress LocalIP=null;
private InetAddress ServerIP=null;
public static void main(String args[]){
GetIP mytest=new GetIP();
System.out.println("LocalHost IP is :" + mytest.catchLocalIP() );
System.out.println("Server IP is :" + mytest.catchServerIP() );
}
//取得本機IP地址
public InetAddress catchLocalIP(){
try{
LocalIP=InetAddress.getLocalHost();
}
catch(UnknownHostException e){
}
return LocalIP;
}
//取得服務器網絡地址
public InetAddress catchServerIP(){
try{
ServerIP=InetAddress.getByName("www.baidu.com");//取得IP 地址
}
catch(UnknownHostException e){
return ServerIP;
}
return ServerIP;
}
}
輸出:
LocalHost IP is :SCOM2987/10.120.0.54
Server IP is :www.baidu.com/220.181.6.175