Java获取IP 地址和主机名称
有些时候我们需要获取一下某些设备的ip地址和名称,无论是pc段的java程序,还是android上。
实际上Java提供了一个java.net.InetAddress类,使用这个类的方法就可以实现由主机名获取ip地址和由ip地址获取主机名的功能。<!--more-->
下面是一段获取本机ip,本机名称和本机全部ip的代码。
结果:
Local Host Ip is 192.168.2.67
the local Host name is ubuntu
One Of Local IPs 192.168.2.67
有些时候我们需要获取一下某些设备的ip地址和名称,无论是pc段的java程序,还是android上。
实际上Java提供了一个java.net.InetAddress类,使用这个类的方法就可以实现由主机名获取ip地址和由ip地址获取主机名的功能。<!--more-->
下面是一段获取本机ip,本机名称和本机全部ip的代码。
import java.net.InetAddress;
public class IPGetterDemo {
//the entrance of application
public static void main(String[] args){
System.out.println("Local Host Ip is "+getLocalHostIP());
String localHostName=getLocalHostName();
System.out.println("the local Host name is "+localHostName);
String[] localIPs=getAllHostIPs(localHostName);
if(null!=localIPs){
for(int i=0;i<localIPs.length;i++){
System.out.println("One Of Local IPs "+localIPs[i]);
}
}
}
/*
* get the local host ip
*/
public static String getLocalHostIP(){
try{
InetAddress addr=InetAddress.getLocalHost();
return addr.getHostAddress();
}catch(Exception e){
return "";
}
}
/*
* get the local host name
*/
public static String getLocalHostName(){
try{
InetAddress addr=InetAddress.getLocalHost();
return addr.getHostName();
}catch(Exception e){
return "";
}
}
/*
* get all host ips by the given hostName
*/
public static String[] getAllHostIPs(String hostName){
String[] ips=null;
try{
InetAddress[] addrs=InetAddress.getAllByName(hostName);
if(null!=addrs){
ips=new String[addrs.length];
for(int i=0;i<addrs.length;i++){
ips[i]=addrs[i].getHostAddress();
}
}
}catch(Exception e){
ips=null;
}
return ips;
}
}
结果:
Local Host Ip is 192.168.2.67
the local Host name is ubuntu
One Of Local IPs 192.168.2.67
One Of Local IPs 0:0:0:0:0:0:0:1
更多技术文章请访问:[url]http://thinkblog.sinaapp.com[/url]