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

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

    From Java Tutorial

    Why is InetAddress not a good solution? I don't see anything in the docs about cross platform compatibility?

    This code will enumerate all network interfaces and retrieve their information.

    import java.io.*;
    import java.net.*;
    import java.util.*;
    import static java.lang.System.out;
    
    public class ListNets 
    {
        public static void main(String args[]) throws SocketException {
            Enumeration nets = NetworkInterface.getNetworkInterfaces();
            for (NetworkInterface netint : Collections.list(nets))
                displayInterfaceInformation(netint);
        }
    
        static void displayInterfaceInformation(NetworkInterface netint) throws SocketException {
            out.printf("Display name: %s\n", netint.getDisplayName());
            out.printf("Name: %s\n", netint.getName());
            Enumeration inetAddresses = netint.getInetAddresses();
            for (InetAddress inetAddress : Collections.list(inetAddresses)) {
                out.printf("InetAddress: %s\n", inetAddress);
            }
            out.printf("\n");
         }
    }  
    

    The following is sample output from the example program:

    Display name: bge0
    Name: bge0
    InetAddress: /fe80:0:0:0:203:baff:fef2:e99d%2
    InetAddress: /121.153.225.59
    
    Display name: lo0
    Name: lo0
    InetAddress: /0:0:0:0:0:0:0:1%1
    InetAddress: /127.0.0.1
    

提交回复
热议问题