How to get the ip of the computer on linux through Java?

前端 未结 5 1338
忘掉有多难
忘掉有多难 2020-12-05 15:56

How to get the ip of the computer on linux through Java ?

I searched the net for examples, I found something regarding NetworkInterface class, but I can\'t wrap my

5条回答
  •  难免孤独
    2020-12-05 16:25

    It's not ok to just return the first non-loopback interface as it might have been created by some software like Parallels. It's a better bet to try fishing for the eth0.

    static private InetAddress getIPv4InetAddress() throws SocketException, UnknownHostException {
    
        String os = System.getProperty("os.name").toLowerCase();
    
        if(os.indexOf("nix") >= 0 || os.indexOf("nux") >= 0) {   
            NetworkInterface ni = NetworkInterface.getByName("eth0");
    
            Enumeration ias = ni.getInetAddresses();
    
            InetAddress iaddress;
            do {
                iaddress = ias.nextElement();
            } while(!(iaddress instanceof Inet4Address));
    
            return iaddress;
        }
    
        return InetAddress.getLocalHost();  // for Windows and OS X it should work well
    }
    

提交回复
热议问题