1

我想获取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(" ");
    }
4

3 回答 3

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());
      }
于 2013-02-24T08:28:06.043 回答
1

我们可以使用 Wifi manager 类来获取设备的 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)
          );
于 2013-06-17T20:12:28.273 回答
0

Wi-Fi Direct场景下如何获取每台设备的IP地址?

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

这些链接可能会对您有所帮助。

于 2012-08-21T10:17:17.687 回答