Search code examples
androidipwifiip-addressandroid-wifi

How to find Ip address of a device via wifi?


i wanna get IP address. Using that Ip address must detect overall devices which is connected to a specific network/device.And should be able to get MAC address ?

 tv=(TextView)findViewById(R.id.tv);
 wifi=(WifiManager)getSystemService(WIFI_SERVICE) ;
 btn=(Button)findViewById(R.id.btn);
 btn.setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View v) {
 try {
 InetAddress inet=InetAddress.getLocalHost();
 Toast.makeText(getApplicationContext(),inet.toString(),Toast.LENGTH_LONG).show();
 } catch (Exception e) {
 System.out.println(" ");
    }

Solution

  • If you want to detect the ip address of the "Emulator" or android device which is connected to any Network then use this code in Your program. it will give you the exact IP Address which the network have assigned to your device.

    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("ServerActivity", ex.toString());
          }