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

前端 未结 5 1332
忘掉有多难
忘掉有多难 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:19

    This code worked 4me:

    import java.net.InetAddress;
    import java.net.NetworkInterface;
    import java.net.SocketException;
    import java.util.Enumeration;
    
    
    public class ShowIp {
    
        public static void main(String[] args) throws SocketException {
            NetworkInterface ni = NetworkInterface.getByName("eth0");
            Enumeration inetAddresses =  ni.getInetAddresses();
    
    
            while(inetAddresses.hasMoreElements()) {
                InetAddress ia = inetAddresses.nextElement();
                if(!ia.isLinkLocalAddress()) {
                    System.out.println("IP: " + ia.getHostAddress());
                }
            }
        }
    
    }
    

提交回复
热议问题