Java getting my IP address

前端 未结 10 2412
没有蜡笔的小新
没有蜡笔的小新 2020-11-27 16:53

I am trying to get my Internet IP address in Java but I keep getting my local address (ie: 127.0.0.1), when my IP address is 192.168.0.xxx

I am using the line:

10条回答
  •  我在风中等你
    2020-11-27 17:35

    //This program is find your exact LAN(Local Machine on which your are       //runing this program) IP Address 
    import java.net.InetAddress;
    import java.net.NetworkInterface;
    import java.net.SocketException;
    import java.util.Enumeration;
    
    public class GetMyIPAddress {
    public static void main(String gks[]) throws SocketException{
        Enumeration e = NetworkInterface.getNetworkInterfaces();
        int ctr=0;
        while(e.hasMoreElements())
        {
            NetworkInterface n = (NetworkInterface) e.nextElement();
            Enumeration ee = n.getInetAddresses();
            while (ee.hasMoreElements() && ctr<3)
            {       ctr++;
                if(ctr==3)
                    break;
                    InetAddress i = (InetAddress) ee.nextElement();
                        if(ctr==2)
                             System.out.println(i.getHostAddress());
    
            }
        }
    }
    
    }
    

提交回复
热议问题