How to get the LAN IP of a client using Java?

前端 未结 5 1060
攒了一身酷
攒了一身酷 2021-02-06 09:22

How can i get the LAN IP-address of a computer using Java? I want the IP-address which is connected to the router and the rest of the network.

I\'ve tried something like

5条回答
  •  佛祖请我去吃肉
    2021-02-06 09:42

    This is a method I've used for a while. It includes a little hack to figure out the externally visible ip-address as well.

    private List getLocalHostAddresses() {
    
        List addresses = new ArrayList();
    
        try {
            Enumeration e = NetworkInterface.getNetworkInterfaces();
    
            while (e.hasMoreElements()) {
                NetworkInterface ni = e.nextElement();
                Enumeration e2 = ni.getInetAddresses();
                while (e2.hasMoreElements())
                    addresses.add(e2.nextElement().getHostAddress());
            }
            URL u = new URL("http://whatismyip.org");
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    u.openStream()));
            addresses.add(in.readLine());
            in.close();
        } catch (Exception ignore) {
        }
    
        return addresses;
    }
    

提交回复
热议问题