2

我想通过代码在android模拟器中获取我的电脑的IP地址....或告诉我获取连接在一个局域网中的所有设备的IP地址以唯一识别每一个......请帮我排序出这个问题

提前致谢

4

2 回答 2

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();
    }
    } 
      }
于 2012-04-13T06:19:28.943 回答
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();
        }
    }
}
于 2012-04-13T06:33:51.167 回答