如何枚举Java中所有已启用的NIC卡的IP地址?

时间:2009-01-30 04:13:37

标签: java networking ip-address

如果没有解析ipconfig的输出,那么有没有人有100%纯粹的java方法呢?

5 个答案:

答案 0 :(得分:51)

这很简单:

try {
  InetAddress localhost = InetAddress.getLocalHost();
  LOG.info(" IP Addr: " + localhost.getHostAddress());
  // Just in case this host has multiple IP addresses....
  InetAddress[] allMyIps = InetAddress.getAllByName(localhost.getCanonicalHostName());
  if (allMyIps != null && allMyIps.length > 1) {
    LOG.info(" Full list of IP addresses:");
    for (int i = 0; i < allMyIps.length; i++) {
      LOG.info("    " + allMyIps[i]);
    }
  }
} catch (UnknownHostException e) {
  LOG.info(" (error retrieving server host name)");
}

try {
  LOG.info("Full list of Network Interfaces:");
  for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
    NetworkInterface intf = en.nextElement();
    LOG.info("    " + intf.getName() + " " + intf.getDisplayName());
    for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
      LOG.info("        " + enumIpAddr.nextElement().toString());
    }
  }
} catch (SocketException e) {
  LOG.info(" (error retrieving network interface list)");
}

答案 1 :(得分:21)

其中一些只适用于JDK 1.6及更高版本(该版本中添加了其中一种方法。)

List<InetAddress> addrList = new ArrayList<InetAddress>();
for(NetworkInterface ifc : NetworkInterface.getNetworkInterfaces()) {
   if(ifc.isUp()) {
      for(InetAddress addr : ifc.getInetAddresses()) {
        addrList.add(addr);
      }
   }
}

在1.6之前,它有点困难 - 直到那时才支持isUp()。

FWIW:Javadocs注意这是获取节点所有IP地址的正确方法:

  

注意:可以使用   getNetworkInterfaces()+ getInetAddresses()   获取所有IP地址   节点

答案 2 :(得分:8)

此代码仅适用于Java 1.6,因为添加了InterfaceAddress代码。

  try
  {
     System.out.println("Output of Network Interrogation:");
     System.out.println("********************************\n");

     InetAddress theLocalhost = InetAddress.getLocalHost();
     System.out.println(" LOCALHOST INFO");
     if(theLocalhost != null)
     {
        System.out.println("          host: " + theLocalhost.getHostName());
        System.out.println("         class: " + theLocalhost.getClass().getSimpleName());
        System.out.println("            ip: " + theLocalhost.getHostAddress());
        System.out.println("         chost: " + theLocalhost.getCanonicalHostName());
        System.out.println("      byteaddr: " + toMACAddrString(theLocalhost.getAddress()));
        System.out.println("    sitelocal?: " + theLocalhost.isSiteLocalAddress());
        System.out.println("");
     }
     else
     {
        System.out.println(" localhost was null");
     }

     Enumeration<NetworkInterface> theIntfList = NetworkInterface.getNetworkInterfaces();
     List<InterfaceAddress> theAddrList = null;
     NetworkInterface theIntf = null;
     InetAddress theAddr = null;

     while(theIntfList.hasMoreElements())
     {
        theIntf = theIntfList.nextElement();

        System.out.println("--------------------");
        System.out.println(" " + theIntf.getDisplayName());
        System.out.println("          name: " + theIntf.getName());
        System.out.println("           mac: " + toMACAddrString(theIntf.getHardwareAddress()));
        System.out.println("           mtu: " + theIntf.getMTU());
        System.out.println("        mcast?: " + theIntf.supportsMulticast());
        System.out.println("     loopback?: " + theIntf.isLoopback());
        System.out.println("          ptp?: " + theIntf.isPointToPoint());
        System.out.println("      virtual?: " + theIntf.isVirtual());
        System.out.println("           up?: " + theIntf.isUp());

        theAddrList = theIntf.getInterfaceAddresses();
        System.out.println("     int addrs: " + theAddrList.size() + " total.");
        int addrindex = 0;
        for(InterfaceAddress intAddr : theAddrList)
        {
           addrindex++;
           theAddr = intAddr.getAddress();
           System.out.println("            " + addrindex + ").");
           System.out.println("            host: " + theAddr.getHostName());
           System.out.println("           class: " + theAddr.getClass().getSimpleName());
           System.out.println("              ip: " + theAddr.getHostAddress() + "/" + intAddr.getNetworkPrefixLength());
           System.out.println("           bcast: " + intAddr.getBroadcast().getHostAddress());
           int maskInt = Integer.MIN_VALUE >> (intAddr.getNetworkPrefixLength()-1);
           System.out.println("            mask: " + toIPAddrString(maskInt));
           System.out.println("           chost: " + theAddr.getCanonicalHostName());
           System.out.println("        byteaddr: " + toMACAddrString(theAddr.getAddress()));
           System.out.println("      sitelocal?: " + theAddr.isSiteLocalAddress());
           System.out.println("");
        }
     }
  }
  catch (SocketException e)
  {
     e.printStackTrace();
  }
  catch (UnknownHostException e)
  {
     e.printStackTrace();
  }

“toMACAddrString”方法如下所示:

public static String toMACAddrString(byte[] a)
{
  if (a == null)
  {
     return "null";
  }
  int iMax = a.length - 1;

  if (iMax == -1)
  {
     return "[]";
  }

  StringBuilder b = new StringBuilder();
  b.append('[');
  for (int i = 0;; i++)
  {
     b.append(String.format("%1$02x", a[i]));

     if (i == iMax)
     {
        return b.append(']').toString();
     }
     b.append(":");
  }
}

和“toIPAddrString”方法在这里:

public static String toIPAddrString(int ipa)
{
   StringBuilder b = new StringBuilder();
   b.append(Integer.toString(0x000000ff & (ipa >> 24)));
   b.append(".");
   b.append(Integer.toString(0x000000ff & (ipa >> 16)));
   b.append(".");
   b.append(Integer.toString(0x000000ff & (ipa >> 8)));
   b.append(".");
   b.append(Integer.toString(0x000000ff & (ipa)));
   return b.toString();
}

我在上面的try / catch中有第一组代码,这个代码名为IPConfig,在一个名为dump()的方法中。然后我只是在IPConfig中放入一个main方法来调用新的IPConfig()。dump(),这样当我想弄清楚一些古怪的网络问题时,我可以看到Java认为正在进行。我发现我的Fedora盒子报告了与Windows不同的信息,因为LocalHost信息导致我的Java程序出现了一些问题。

我意识到它与其他答案类似,但它打印出几乎所有有趣的东西,你可以从界面和ipaddress apis。

答案 3 :(得分:4)

更新以修复Jared对JDK 1.7的回答。

// Get list of IP addresses from all local network interfaces. (JDK1.7)
// -----------------------------------------------------------
public List<InetAddress> getListOfIPsFromNIs(){
    List<InetAddress> addrList           = new ArrayList<InetAddress>();
    Enumeration<NetworkInterface> enumNI = NetworkInterface.getNetworkInterfaces();
    while ( enumNI.hasMoreElements() ){
        NetworkInterface ifc             = enumNI.nextElement();
        if( ifc.isUp() ){
            Enumeration<InetAddress> enumAdds     = ifc.getInetAddresses();
            while ( enumAdds.hasMoreElements() ){
                InetAddress addr                  = enumAdds.nextElement();
                addrList.add(addr);
                System.out.println(addr.getHostAddress());   //<---print IP
            }
        }
    }
    return addrList;
}

正如Sam Skuce评论所强调的那样:

  

这不能在JDK 1.7中编译。 getNetworkInterfaces返回一个不实现Iterable的Enumeration。 - Sam Skuce 12年11月11日19:58

输出示例:

fe80:0:0:0:800:aaaa:aaaa:0%8
192.168.56.1
fe80:0:0:0:227:aaa:aaaa:6b5%2
123.123.123.123
0:0:0:0:0:0:0:1%1
127.0.0.1

答案 4 :(得分:1)

import java.net.*;
import java.util.*;

public class NIC {

public static void main(String args[]) throws Exception {

    List<InetAddress> addrList = new ArrayList<InetAddress>();
    Enumeration<NetworkInterface> interfaces = null;
    try {
        interfaces = NetworkInterface.getNetworkInterfaces();
    } catch (SocketException e) {
        e.printStackTrace();
    }

    InetAddress localhost = null;

    try {
        localhost = InetAddress.getByName("127.0.0.1");
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }

    while (interfaces.hasMoreElements()) {
        NetworkInterface ifc = interfaces.nextElement();
        Enumeration<InetAddress> addressesOfAnInterface = ifc.getInetAddresses();

        while (addressesOfAnInterface.hasMoreElements()) {
            InetAddress address = addressesOfAnInterface.nextElement();

            if (!address.equals(localhost) && !address.toString().contains(":")) {
                addrList.add(address);
                System.out.println("FOUND ADDRESS ON NIC: " + address.getHostAddress());
            }
        }
    }

}
}