code to detect the Android Device's own Ip Add

2019-05-31 15:35发布

问题:

I want to know about the code which can detect the Ip address and the Android client name of the Android Device so that use this Ip Address and client name in our application.

Can Anyone Help me please... Thanks in Advance.

回答1:

This will tell you your own IP Andress if you run this on your Android Phone.

try{
      InetAddress ownIP=InetAddress.getLocalHost();
      System.out.println("IP of my Android := "+ownIP.getHostAddress());
      }catch (Exception e){
      System.out.println("Exception caught ="+e.getMessage());
      }

If you want to know the IP address of any the client which binds with your applicaion use

Socket socket = serverSocket.accept();  // accept connection                                            


                    System.out.println("Remote IP:"+socket.getInetAddress());

                    System.out.println("Remote Port:"+socket.getPort());                


回答2:

public String getLocalIpAddress()
{
    try {
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
            NetworkInterface intf = en.nextElement();
            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress()) {
                    return inetAddress.getHostAddress().toString();
                }
             }
         }
     } catch (SocketException ex) {
         Log.e(LOG_TAG, ex.toString());
     }

     return null;
}


标签: android ip