private static InetAddress getLinuxLocalIp() throws SocketException { Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces(); InetAddress ip = null; while (netInterfaces.hasMoreElements()) { NetworkInterface ni = (NetworkInterface) netInterfaces .nextElement(); logger.error("ni.getName():"+ni.getName()); Enumeration<InetAddress> ips = ni.getInetAddresses(); while (ips.hasMoreElements()) { ip = ips.nextElement(); logger.error("ip.isSiteLocalAddress():"+ip.isSiteLocalAddress()); logger.error("ip.isLoopbackAddress():"+ip.isLoopbackAddress()); logger.error("ip.getHostAddress():"+ip.getHostAddress()); if (ip != null && ip instanceof Inet4Address && ip.getHostAddress().indexOf(".") != -1) {// 1.获取符合条件的ip //return ip; } else { ip = null; } } } return null; } 代码如上,在测试环境上打印出来的语句如下: 代码放到正式环境下打印日志如下: 遍历时要获取我想要的Inet4Address 地址,但是有那么多不是我想要的,怎么把它们过滤掉?看网上的方法都是判断红色日志中的内容,但是为什么测试环境是true false,正式环境中却是false false? |
|
CSDN好冷清。。。
|
|
5分 |
机器上有多块网卡,会显示多个ip地址。。这个只能根据网段来判断那个是你需要的ip
|
5分 |
NetworkInterface调用getDisplayName方法
显示网卡名称 判定 是服务器使用的网卡名,则区其IP地址 |
15分 |
试试这个代码
import java.net.InterfaceAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.Enumeration; import java.util.Iterator; import java.util.List; /** * @author suzhw<br> * 日期:2014-10-14<br> * 功能:根据启动并运行的网卡名称,找到本机实际的IP地址(已知当前运行的无线网卡名包含“wireless”字段)<br> * 版权:版权所有(C) 2014,suzhw<br> * @version v0.1 * @see */ public class ToGetLocalLinkIP2 { public static void main(String[] args) throws Exception { Enumeration<NetworkInterface> en = NetworkInterface .getNetworkInterfaces(); while (en.hasMoreElements()) { NetworkInterface ni = en.nextElement(); printParameter(ni); } } public static void printParameter(NetworkInterface ni) throws SocketException { if (null != ni.getDisplayName() && ni.getDisplayName().contains("Wireless") && ni.isUp()) { System.out.println(" Name = " + ni.getName()); System.out.println(" Display Name = " + ni.getDisplayName()); System.out.println(" Is up = " + ni.isUp()); System.out .println(" Support multicast = " + ni.supportsMulticast()); System.out.println(" Is loopback = " + ni.isLoopback()); System.out.println(" Is virtual = " + ni.isVirtual()); System.out.println(" Is point to point = " + ni.isPointToPoint()); System.out .println(" Hardware address = " + ni.getHardwareAddress()); System.out.println(" MTU = " + ni.getMTU()); System.out.println("\nList of Interface Addresses:"); List<InterfaceAddress> list = ni.getInterfaceAddresses(); Iterator<InterfaceAddress> it = list.iterator(); while (it.hasNext()) { InterfaceAddress ia = it.next(); if(null!=ia.getBroadcast()){ System.out.println(" 本机实际联网网卡IPv4地址: " + ia.getAddress().getHostAddress()); } } System.out .println("**************************************************"); } } } |