您的位置:首页 > 运维架构 > Linux

JAVA分别实现Windows平台和Linux平台下的ip获取

2014-10-28 17:15 411 查看
一般我们很容易获取Windows系统下的ip信息,比如:

package com.han;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
* 程序实现了Windows平台下获得本机ip地址
* @author HAN
*
*/
public class InetAddressObtainment_Windows {
String hostname;
String hostaddress;
void initialize(){
try {
InetAddress ia=InetAddress.getLocalHost(); //获得本机网络地址对象
hostname=ia.getHostName(); //获得对应主机名
hostaddress=ia.getHostAddress(); //获得对应主机地址
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args){
InetAddressObtainment_Windows o1=new InetAddressObtainment_Windows();
System.out.println(o1.hostname);
System.out.println(o1.hostaddress);
o1.initialize();
System.out.println(o1.hostname);
System.out.println(o1.hostaddress);
}
}
但是我们确发现在Linux下运行上面的代码确实获得我的本机Linux默认设定的地址(Linux中有一文件自动使用了ip变换),当然你可以去usr等相关文件夹去修改ip映射。但是我出于好奇,想单纯从JAVA角度去实现获取。故随便没事写了下面的程序:

package com.han;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
/**
* 程序实现了Linux平台下获得本机ip地址。由于和Windows平台不同,不能用经典的方式查看。
* <p>
* 但是可以通过查询网络接口(NetworkInterface)的方式来实现。
* <p>
* 本程序中同样运用了JAVA核心技术:枚举类型。
* <p>
* 枚举类型不仅可以使程序员少写某些代码,主要还提供了编译时的安全检查,可以很好的解决类安全问题。
* 我们写JAVA代码时应该有意识去使用。
* @author HAN
*
*/
class InetAddressObtainment_Linux{
public static void main(String[] args){
Enumeration<NetworkInterface> allNetInterfaces;  //定义网络接口枚举类
try {
allNetInterfaces = NetworkInterface.getNetworkInterfaces();  //获得网络接口

InetAddress ip = null; //声明一个InetAddress类型ip地址
while (allNetInterfaces.hasMoreElements()) //遍历所有的网络接口
{
NetworkInterface netInterface = allNetInterfaces.nextElement();
System.out.println(netInterface.getName());  //打印网端名字
Enumeration<InetAddress> addresses = netInterface.getInetAddresses(); //同样再定义网络地址枚举类
while (addresses.hasMoreElements())
{
ip = addresses.nextElement();
if (ip != null && (ip instanceof Inet4Address)) //InetAddress类包括Inet4Address和Inet6Address
{
System.out.println("本机的IP = " + ip.getHostAddress());
}
}
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}


转自:http://blog.csdn.net/gaowen_han/article/details/7163752
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: