如何通过wifi找到设备的IP地址?

时间:2012-08-21 10:02:08

标签: android ip wifi ip-address android-wifi

我想获得IP地址。使用该IP地址必须检测连接到特定网络/设备的整体设备。应该能够获得MAC地址吗?

 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(" ");
    }

3 个答案:

答案 0 :(得分:3)

如果要检测连接到任何网络的“仿真器”或Android设备的IP地址,请在您的程序中使用此代码。它将为您提供网络为您的设备分配的确切IP地址。

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());
      }

答案 1 :(得分:1)

我们可以使用Wifi经理类来获取设备的IP地址:

在清单

中添加“ACCESS_WIFI_STATE”权限
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)
          );

答案 2 :(得分:0)