使用InetAddress来收集网络接口

huangapple go评论77阅读模式
英文:

Using InetAddress to gather network interfaces

问题

我已经将您提供的内容翻译如下:

我已经将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();
}
}

请注意,我只翻译了您提供的Java代码部分。如有需要,请随时提问。

英文:

I have used InetAddress as an array. However if i do not use array, I am able to print each network interface in the loop. Though I am iterating the array of InetAddress, the code shows nothing. Is there a fundamental problem? I am very new to networking world in 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();
}

}

答案1

得分: 1

发生了 SocketException。您没有将它打印出来,也没有对它做任何处理,因此后续没有任何操作,您也无法看到它。如果您使用类似 exp.printStackTrace() 的方法,而不是 exp.getCause()(它不会做任何操作),您将会看到这个问题。

英文:

A SocketException is occurring. You do not print it, or do anything with it, so nothing happens afterwards, and you do not see it. If instead of exp.getCause() (which does nothing) you do something like exp.printStackTrace() you will see the problem.

huangapple
  • 本文由 发表于 2020年8月18日 01:22:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/63455704.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定