1

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(" ");
    }
Nicos Karalis
  • 3,724
  • 4
  • 33
  • 62
Achiever
  • 1,626
  • 10
  • 30
  • 54

3 Answers3

3

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());
      }
Pir Fahim Shah
  • 10,505
  • 1
  • 82
  • 81
1

We can use Wifi manager class to get the IP address of device :

Add "ACCESS_WIFI_STATE" permission in manifest

WifiManager myWifiManager = (WifiManager)getSystemService(Context.WIFI_SERVICE);

WifiInfo myWifiInfo = myWifiManager.getConnectionInfo();
//gets the Ip address in hex form, We need to convert it to integer and then finally to string to display it 

int myIp = myWifiInfo.getIpAddress();     
int intMyIp3 = myIp/0x1000000;
int intMyIp3mod = myIp%0x1000000;

int intMyIp2 = intMyIp3mod/0x10000;
int intMyIp2mod = intMyIp3mod%0x10000;

int intMyIp1 = intMyIp2mod/0x100;
int intMyIp0 = intMyIp2mod%0x100;

t3.setText(String.valueOf(intMyIp0) + "." + String.valueOf(intMyIp1)
                    + "." + String.valueOf(intMyIp2)
                    + "." + String.valueOf(intMyIp3)
          );
Nunser
  • 4,512
  • 8
  • 25
  • 37
0

How to get each device's IP address in Wi-Fi Direct scenario?

http://developer.android.com/guide/topics/connectivity/wifip2p.html

these links may help you.

Community
  • 1
  • 1
Nikhil Dinesh
  • 3,359
  • 2
  • 38
  • 41
  • Actually i am working on Android 2.3 and sdk 10 . Those links support only Android 4.0 . Do u have any codes for android 2.3 ? – Achiever Aug 21 '12 at 10:36
  • http://stackoverflow.com/questions/10683495/android-how-to-know-an-ip-address-is-a-wifi-ip-address – Nikhil Dinesh Aug 21 '12 at 10:57