Java gets the IP address assigned to the computer by the local router and is related to the host name

I recently worked on a PC-side project and encountered a communication problem related to ip address. After some inquiries on the Internet, I think this method is relatively good at present, so I will make a record here. If you pass by, if there is a better method , Please leave the answer and let the younger brother learn from it.
Let's enter the main question, first get the ip address of the machine, which is relatively simple (mainly through the cmd command arp -a to get all the cache addresses of the current computer and the corresponding table of ip addresses), The following code

public class GoodWindowsExec {
    @SuppressWarnings("unused")
    public static ArrayList<String> exec(String cmdLine) {
        ArrayList<String>   lines  = new ArrayList<>();
        try {
            String osName = System.getProperty("os.name");
            String[] cmd = new String[3];
            cmd[0] = "cmd.exe";
            cmd[1] = "/C";
            cmd[2] = cmdLine;
            Runtime rt = Runtime.getRuntime();
            Process proc = rt.exec(cmd);
            InputStreamReader ir = new InputStreamReader(proc.getInputStream(),"gbk");
            LineNumberReader input = new LineNumberReader(ir);  
            String line = null;
            while ((line = input.readLine()) != null){
                System.out.println(line);
                lines.add(line);
        }
            // any error???
            int exitVal = proc.waitFor();
            System.out.println("ExitValue: " + exitVal);
        } catch (Throwable t) {
            t.printStackTrace();
        }
        return lines;
    }

    public static void main(String args[]) {
        exec("arp -a");
        Enumeration<NetworkInterface> nets = NetworkInterface
                .getNetworkInterfaces();
        for (NetworkInterface netint : Collections.list(nets))
        if (null != netint.getHardwareAddress()) {
            List<InterfaceAddress> list = netint.getInterfaceAddresses();
            for (InterfaceAddress interfaceAddress : list) {
                String localip=interfaceAddress.getAddress().toString();
                    System.out.println("======="+localip+"===========");
            }
        }
    }

Because the PC client on my side needs to know the current ip address of the lower computer, and I only know the host name of the lower computer, so I get the ip address of the local computer, and then traverse the ping to the ip address that can be pinged under the LAN Then put it into the collection, and traverse the hostname matching corresponding to these addresses, the code is as follows:

public class IP {
    static public HashMap<String,String> ping; // ping 后的结果集
    static ArrayList<String> actives  = new ArrayList<>();
    public HashMap<String,String>  getPing() { // 用来得到ping后的结果集
        return ping;
    }
    public static long begin;

    // 当前线程的数量, 防止过多线程摧毁电脑
    static int threadCount = 0;

    public IP() {
        ping = new HashMap<String,String> ();
    }

    public void Ping(String ip) throws Exception {
        // 最多30个线程
        while (threadCount > 30)
            Thread.sleep(50);
        threadCount += 1;
        PingIp p = new PingIp(ip);
        p.start();
    }

    public void PingAll() throws Exception {
        // 首先得到本机的IP,得到网段
        String localip =  ListNets.getAllLocalIp().get(0).substring(1,ListNets.getAllLocalIp().get(0).length());
        int k = 0;
        k = localip.lastIndexOf(".");
        String ss = localip.substring(0, k + 1);
        Controller.IP3 = ss;
        for (int i = 1; i <= 255; i++) { // 对所有局域网Ip
            String iip = Controller.IP3 + i;
            Ping(iip);
        }
    }
    class PingIp extends Thread {
        public String ip; // IP

        public PingIp(String ip) {
            this.ip = ip;
        }

        public void run() {
            try {
                Process p = Runtime.getRuntime().exec("ping  " + ip + " -w 300 -n 1");
                InputStreamReader ir = new InputStreamReader(p.getInputStream(),"gbk");
                LineNumberReader input = new LineNumberReader(ir);  
                // 读取结果行
                for (int i = 1; i < 7; i++){
                    input.readLine();
                }
                String line = input.readLine();
                if (line == null ||  line.length() < 17 || line.substring(8, 17).equals("timed out"))
                    ping.put(ip, "None");
                else
                    actives.add(ip);
                // 线程结束
                threadCount -= 1;
            } catch (IOException e) {
            }

        }

    }

    public ArrayList<String> getCrIP() throws Exception {
        PingAll();
        ArrayList<String> crip;
        crip = actives;
        return crip;
    }
public class ConnectThread  extends Thread{
    @Override
    public void run() {
        IP ip = new IP();
        ArrayList<String> lines =new ArrayList<>();
        try {
            lines = ip.getCrIP();
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
         ArrayList<String>  ips = new ArrayList<>();
         for(String line:lines){
             try {
                String localip =  ListNets.getAllLocalIp().get(0).substring(1,ListNets.getAllLocalIp().get(0).length());
                int k = 0;
                k = localip.lastIndexOf(".");
                String ss = localip.substring(0, k + 1);
                Controller.IP3 = ss;
                if(line.indexOf(Controller.IP3) ==0){
                    String[] s = line.trim().split(" ");
                    ips.add(s[0].trim());
                }
            } catch (SocketException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

         }
         for(int i=0;i<ips.size();i++){
                byte[] address=toIpByte(ips.get(i));
                InetAddress addr;
                try {
                    addr = InetAddress.getByAddress(address);
                    String hostname = addr.getHostName();
                    if(hostname.length()>5 && (hostname.indexOf("下位机主机名")==0)){
                        return;
                    }
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
         }
    }


     private static byte[] toIpByte(String ip) {
            String[] ips=ip.split("\\.");
            byte[] address=new byte[ips.length];
            for (int i=0;i<ips.length;i++){
                address[i]=(byte) Integer.parseInt(ips[i]);
            }
            return address;
        }

     public static void main(String[] args) {
         ConnectThread c = new ConnectThread();
         c.start();
    }

}

This approach is that when starting the PC, the startup speed of pingip will be slightly slower, which will affect the customer's experience, so I hope some friends who have a better way can leave a message for the younger brother, thank you!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325708104&siteId=291194637