首页 > 解决方案 > 使用 InetAddress 收集网络接口

问题描述

我使用 InetAddress 作为数组。但是,如果我不使用数组,我可以在循环中打印每个网络接口。虽然我正在迭代 InetAddress 数组,但代码没有显示任何内容。有根本问题吗?我对java中的网络世界很陌生。

import java.io.*;
import java.net.*;
import java.util.*;
public class Interface_Enumeration_Concept {
   InetAddress[] address;
   public void GetInterfaces(){
    try {
        Enumeration interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface intf = (NetworkInterface) interfaces.nextElement();
            Enumeration addresses = intf.getInetAddresses();
            int i=0;
            while (addresses.hasMoreElements()){
                address[i] = (InetAddress) addresses.nextElement();
                System.out.println(address[i]);
                i++;
            }
        }
    }catch(SocketException exp){
        exp.getCause();
    }
}
public static void main(String[] args) {
    Interface_Enumeration_Concept objects = new Interface_Enumeration_Concept();
    objects.GetInterfaces();
}

}

标签: javanetworking

解决方案


ASocketException正在发生。你不打印它,也不用它做任何事情,所以之后什么也没有发生,你也看不到它。如果不是exp.getCause()(什么都不做)你做一些exp.printStackTrace()你会看到问题的事情。


推荐阅读