微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用Java 1.5在Windows中获取以太网适配器的IPv4地址

问题

我的Windows系统有多个以太网适配器.鉴于以太网适配器的名称,我需要找到它的IP地址.

例如,我系统的ipconfig命令的输出是:

Ethernet adapter GB1:

   Connection-specific DNS Suffix  . : 
   IP Address. . . . . . . . . . . . : 0.0.0.0
   subnet Mask . . . . . . . . . . . : 0.0.0.0
   Default Gateway . . . . . . . . . : 

Ethernet adapter SWITCH:

   Connection-specific DNS Suffix  . : 
   IP Address. . . . . . . . . . . . : 10.200.1.11
   subnet Mask . . . . . . . . . . . : 255.255.255.0
   IP Address. . . . . . . . . . . . : 10.200.1.51
   subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . : 

Ethernet adapter LAN:

   Connection-specific DNS Suffix  . : 
   IP Address. . . . . . . . . . . . : 10.1.2.62
   subnet Mask . . . . . . . . . . . : 255.255.254.0
   IP Address. . . . . . . . . . . . : 10.1.2.151
   subnet Mask . . . . . . . . . . . : 255.255.254.0
   Default Gateway . . . . . . . . . : 10.1.2.1

注意:我不必担心无线适配器或任何其他类型的适配器.我只需要为以太网适配器执行此操作.

对于这个系统,我需要编写一个行为如下所示的java类

C:>java NametoIp GB1
0.0.0.0

C:>java NametoIp SWITCH
10.200.1.11
10.200.1.51

C:>java NametoIp LAN
10.1.2.62
10.1.2.151

什么行不通

使用java.net.NetworkInterface没有帮助.它的getName()getDisplayName()方法不会打印出现在ipconfig输出或Windows网络连接中的适配器连接名称.它们会打印实际的设备名称.例如,请考虑以下代码

import java.util.Enumeration;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.socketException;
import java.net.UnkNownHostException;

public class ListInterfaces 
{
    public static void main(String[] args) throws SocketException,UnkNownHostException {

        Enumeration<NetworkInterface> nwInterfaces = NetworkInterface.getNetworkInterfaces();

        while (nwInterfaces.hasMoreElements()) {

            NetworkInterface nwInterface = nwInterfaces.nextElement();
            System.out.print(nwInterface.getName() + ": " +
                             nwInterface.getdisplayName());

            Enumeration<InetAddress> addresses = nwInterface.getInetAddresses();
            while (addresses.hasMoreElements()) {
                InetAddress address = addresses.nextElement();
                System.out.print(" - " + address.getHostAddress());
            }
            System.out.println();
        }
    }
}

这将打印以下输出

C:>java ListInterfaces
lo: MS TCP Loopback interface - 127.0.0.1
eth0: broadcom BCM5709C NetXtreme II GigE (Ndis VBD Client) # 
eth1: broadcom BCM5709C NetXtreme II GigE (Ndis VBD Client) #2 - 10.200.1.11 - 10.200.1.51
eth2: broadcom BCM5709C NetXtreme II GigE (Ndis VBD Client) #3 - 10.1.2.62 - 10.1.2.151

一个丑陋的黑客行事

我编写了一个丑陋的黑客,它从ipconfig输出提取指定适配器名称的IP地址.这是代码.

import java.util.ArrayList;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
import java.io.IOException;

public class NametoIp
{
    public static ArrayList<String> getIP(String adapterName)
    throws IOException,InterruptedException
    {
        // Run the Windows 'ipconfig' command and get its stdout
        ProcessBuilder cmdBuilder = new ProcessBuilder("ipconfig");
        Process process = cmdBuilder.start();
        BufferedReader stdout = new BufferedReader(
                new InputStreamReader(process.getInputStream()));

        // Find the section for the specified adapter
        String line;
        boolean foundAdapter = false;
        while ((line = stdout.readLine()) != null) {
            line = line.trim();
            if (line.equals("Ethernet adapter " + adapterName + ':')) {
                foundAdapter = true;
                break;
            }
        }
        if (!foundAdapter) {
            process.waitFor();
            throw new IOException("Adapter not found");
        }

        // Find IP addresses in the found section
        ArrayList<String> ips = new ArrayList<String>();
        while ((line = stdout.readLine()) != null) {
            // Stop parsing if we reach the beginning of the next
            // adapter section in the output of ifconfig
            if (line.length() > 0 && line.charat(0) != ' ') {
                break;
            }

            line = line.trim();

            // Extract IP addresses
            if (line.startsWith("IP Address.") ||
                line.startsWith("IPv4 Address.")) {

                int colonIndex;
                if ((colonIndex = line.indexOf(':')) != 1) {
                    ips.add(line.substring(colonIndex + 2));
                }
            }
        }
        process.waitFor();

        return ips;
    }

    public static void main(String[] args)
    throws IOException,InterruptedException
    {
        // Print help message if adapter name has not been specified
        if (args.length != 1) {
            StackTraceElement[] stack = Thread.currentThread().getStackTrace();
            String prog = stack[stack.length - 1].getClassName();

            System.err.println("Usage: java " + prog + " ADAPTERNAME");
            System.err.println("Examples:");
            System.err.println("  java " + prog +" \"Local Area Connection\"");
            System.err.println("  java " + prog +" LAN");
            System.err.println("  java " + prog +" SWITCH");
            System.exit(1);
        }

        ArrayList<String> ips = getIP(args[0]);
        for (String ip: ips) {
            System.out.println(ip);
        }
    } 
}

有没有更好的方法解决这个问题?

解决方法

创建一个使用Windows API查询本地以太网地址并使用JNI调用dll的DLL.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


应用场景 C端用户提交工单、工单创建完成之后、会发布一条工单创建完成的消息事件(异步消息)、MQ消费者收到消息之后、会通知各处理器处理该消息、各处理器处理完后都会发布一条将该工单写入搜索引擎的消息、最终该工单出现在搜索引擎、被工单处理人检索和处理。 事故异常体现 1、异常体现 从工单的流转记录发现、
线程类,设置有一个公共资源 package cn.org.chris.concurrent; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * @Descrip
Java中的数字(带有0前缀和字符串)
在Java 9中使用JLink的目的是什么?
Java Stream API Filter(过滤器)
在Java中找到正数和负数数组元素的数量
Java 9中JShell中的不同启动脚本是什么?
使用Java的位填充错误检测技术
java中string是什么
如何使用Java中的JSON-lib API将Map转换为JSON对象?