这是另一个实现获取主机名称,IP地址类.可以获取本机的名称,IP和指定域名的主机名称,IP.返回值为字串型,可以在其它Java类或JSP中引用.
/**
*实现获取主机名称,IP地址的类.
*<br>Copyright (C) ☆苹果工作室☆
*/
package com.applestudio.util;
import java.net.*;
public class Network1{
InetAddress inet=null;
public static void main( String args[]){
Network1 network=new Network1();
System.out.println("Your host IP is: "+ network.getLIP());
System.out.println("Your host Name is: "+ network.getLName());
System.out.println();
System.out.println("The Server IP is :"+network.getRIP("www.sohu.com"));
System.out.println("The Server Name is :"+network.getRName("199.181.132.250"));
}
//取得Localhost的IP地址
private String getLIP() {
return getLAddress().getHostAddress();
}
//取得Localhost的主机名称
private String getLName() {
return getLAddress().getHostName();
}
//取得Remotehost的IP地址
private String getRIP(String host){
return getRAddress(host).getHostAddress();
}
//取得Remotehost的主机名称
private String getRName(String ip) {
return getRAddress(ip).getHostName();
}
private InetAddress getLAddress() {
try {
inet=InetAddress.getLocalHost();
}catch(UnknownHostException e) {}
return (inet);
}
public InetAddress getRAddress(String IP_or_Name){
try {
inet=InetAddress.getByName(IP_or_Name);
}catch (UnknownHostException e) {}
return (inet);
}
}