46

の出力を解析する以外にipconfig、これを行う 100% 純粋な Java の方法を持っている人はいますか?

4

5 に答える 5

8

このコードは、InterfaceAddress コードが追加されているため、Java 1.6 でのみ機能します。

  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 メソッドを配置して new IPConfig().dump() を呼び出し、奇抜なネットワークの問題を見つけようとしているときに、Java が考えていることを確認できるようにします。私の Fedora ボックスは、LocalHost 情報について Windows とは異なる情報を報告し、Java プログラムにいくつかの問題を引き起こしていることがわかりました。

他の回答と似ていることは理解していますが、インターフェイスと ipaddress API から取得できる興味深いものはほとんどすべて出力されます。

于 2009-01-30T13:51:46.080 に答える
4

JDK 1.7 に対する Jared の回答を修正するための更新。

// 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 を返します。— サム スクース

出力例:

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
于 2013-03-26T15:28:20.687 に答える
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());
            }
        }
    }

}
}
于 2011-04-14T09:03:54.523 に答える