Java 使用InetAddress收集网络接口
我使用InetAddress作为数组。但是,如果我不使用数组,我可以打印循环中的每个网络接口。虽然我正在迭代InetAddress数组,但代码没有显示任何内容。有一个根本性的问题吗?我对java的网络世界非常陌生Java 使用InetAddress收集网络接口,java,networking,Java,Networking,我使用InetAddress作为数组。但是,如果我不使用数组,我可以打印循环中的每个网络接口。虽然我正在迭代InetAddress数组,但代码没有显示任何内容。有一个根本性的问题吗?我对java的网络世界非常陌生 import java.io.*; import java.net.*; import java.util.*; public class Interface_Enumeration_Concept { InetAddress[] address; public void
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();
}
}正在发生SocketException。您不打印它,也不使用它做任何事情,因此之后不会发生任何事情,您也看不到它。如果您不使用exp.getCause,而使用exp.printStackTrace,您将看到问题。当您修复该问题时,您将得到一个NullPointerException,因为您尚未初始化地址。是的,我没有。在皮特的《java网络基础》一书中。他没有通过构造函数初始化InetAddress。只需声明它并填充值。它起作用了