通过代码android获取Android模拟器上的pc的ip地址

时间:2012-04-13 06:12:55

标签: android android-emulator ip

我想通过代码在Android模拟器中获取我的电脑的IP地址....或者告诉我在一个局域网中连接的所有设备的IP地址,以确定每一个独特的.......请帮助我解决这个问题

提前致谢

2 个答案:

答案 0 :(得分:2)

使用此代码获取外部IP地址

      HttpClient httpclient = new DefaultHttpClient();
      HttpGet httpget = new HttpGet("http://api.externalip.net/ip/"); 
      HttpResponse response = null;
      try 
      {
      response = httpclient.execute(httpget);
        } 
      catch (ClientProtocolException e)
      {
     e.printStackTrace();
        } 
      catch (IOException e)
      {
     e.printStackTrace();
        }
      Log.e("",""+response);
      HttpEntity entity = response.getEntity();
      if (entity != null) {
      long len = entity.getContentLength();
      if (len != -1 && len < 1024) 
      {
       try
       {
      str=EntityUtils.toString(entity);
       Log.e("",""+str);
        }
       catch (ParseException e)
       {            
    e.printStackTrace();
    } 
       catch (IOException e)
       {                
    e.printStackTrace();
    }
    } 
      }

答案 1 :(得分:2)

上述功能只能通过检查arp缓存来实现,其中IP地址将逐个添加,具体取决于每个连接到设备的方式。使用以下代码并检查。只需按下具有正确名称的按钮,然后单击

调用此方法
    public void getClientList() {

    int macCount = 0;
    BufferedReader br = null;
    try {
        br = new BufferedReader(new FileReader("/proc/net/arp"));
        String line;
        while ((line = br.readLine()) != null) {
            String[] splitted = line.split(" +");

            if (splitted != null && splitted.length >= 4) {
                // Basic sanity check
                String mac = splitted[3];

                if (mac.matches("..:..:..:..:..:..")) {
                    macCount++;
                    ClientList.add("Client(" + macCount + ")");
                    IpAddr.add(splitted[0]);
                    HWAddr.add(splitted[3]);
                    Device.add(splitted[5]);
                    Toast.makeText(
                            getApplicationContext(),
                            "Mac_Count  " + macCount + "   MAC_ADDRESS  "
                                    + mac, Toast.LENGTH_SHORT).show();
                    for (int i = 0; i < splitted.length; i++)
                        System.out.println("Addressssssss     "
                                + splitted[i]);
                }
            }
        }
        // ClientList.remove(0);

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}