InetAddress获取本地计算机IP地址
有时需要获取本机的ip地址,简单的记录一下:
//获取单个IP地址
public static String getLocalHostIP() {
String ip;
try {
InetAddress addr = InetAddress.getLocalHost();
ip = addr.getHostAddress();
} catch(Exception ex) {
ip = "";
}
return ip;
}
//获取主机名称
public static String getLocalHostName() {
String hostName;
try {
InetAddress addr = InetAddress.getLocalHost();
hostName = addr.getHostName();
}catch(Exception ex){
hostName = "";
}
return hostName;
}
//获取所有的IP地址
public static String[] getAllLocalHostIP() {
String[] ret = null;
try {
String hostName = getLocalHostName();
if(hostName.length()>0) {
InetAddress[] addrs = InetAddress.getAllByName(hostName);
if(addrs.length>0) {
ret = new String[addrs.length];
for(int i=0 ; i< addrs.length ; i++) {
ret[i] = addrs[i].getHostAddress();
}
}
}
}catch(Exception ex) {
ret = null;
}
return ret;
}
同时有时候需要获取某个网站的IP,可以使用以下代码:
InetAddress baidu;
try {
baidu = InetAddress.getByName("www.baidu.com");
System.out.println("baidu : " + baidu);
System.out.println("baidu IP: " + baidu.getHostAddress());
System.out.println("baidu HostName: " + baidu.getHostName());
} catch (UnknownHostException e) {
e.printStackTrace();
}