使用电话作为接入点的设备的 IP 地址

发布于 2024-12-19 01:13:30 字数 1122 浏览 2 评论 0原文

任何人都可以解释或展示如何获取通过手机的便携式 WI-FI 热点连接的计算机(或其他设备)的 IP 地址吗?

我在此处

public String getLocalIpAddress() {
    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(LOG_TAG, ex.toString());
    }
    return null;
}

但这仅返回默认网关。

我还发现另一个例子< /a> 在这里,这可能只是解决方案,但我不知道如何将其应用于我的情况。具体来说,我看不到 IP 地址在那段代码中的位置。

Can anyone explain or show how to get the IP address of a computer (or other device) that's connected through the phone's portable WI-FI hotspot?

I tried the following code from here

public String getLocalIpAddress() {
    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(LOG_TAG, ex.toString());
    }
    return null;
}

But that only returns the default gateway.

I also found another example here on SO, and it might just be the solution, but I don't know how to apply it to my situation. Specifically I cannot see where the IP address is in that piece of code.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

千纸鹤 2024-12-26 01:13:30

以下代码将为您提供 ip 地址和连接到 Android 热点设备的支持 wifi 的设备的其他详细信息

Main.java

import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import com.whitebyte.hotspotclients.R;
import com.whitebyte.wifihotspotutils.ClientScanResult;
import com.whitebyte.wifihotspotutils.WifiApManager;

public class Main extends Activity {
      TextView textView1;
      WifiApManager wifiApManager;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    textView1 = (TextView) findViewById(R.id.textView1);
    wifiApManager = new WifiApManager(this);

    scan();
}

private void scan() {
    ArrayList<ClientScanResult> clients = wifiApManager.getClientList(false);

    textView1.append("Clients: \n");
    for (ClientScanResult clientScanResult : clients) {
        textView1.append("####################\n");
        textView1.append("IpAddr: " + clientScanResult.getIpAddr() + "\n");
        textView1.append("Device: " + clientScanResult.getDevice() + "\n");
        textView1.append("HWAddr: " + clientScanResult.getHWAddr() + "\n");
        textView1.append("isReachable: " + clientScanResult.isReachable() + "\n");
    }
}

ClientScanResult.java

public class ClientScanResult {

private String IpAddr;

private String HWAddr;

private String Device;

private boolean isReachable;

public ClientScanResult(String ipAddr, String hWAddr, String device, boolean isReachable) {
    super();
    IpAddr = ipAddr;
    HWAddr = hWAddr;
    Device = device;
    this.setReachable(isReachable);
}

public String getIpAddr() {
    return IpAddr;
}

public void setIpAddr(String ipAddr) {
    IpAddr = ipAddr;
}

public String getHWAddr() {
    return HWAddr;
}

public void setHWAddr(String hWAddr) {
    HWAddr = hWAddr;
}

public String getDevice() {
    return Device;
}

public void setDevice(String device) {
    Device = device;
}

public void setReachable(boolean isReachable) {
    this.isReachable = isReachable;
}

public boolean isReachable() {
    return isReachable;
}

}

WIFI_AP_STATE.java

     public enum WIFI_AP_STATE 
     {
        WIFI_AP_STATE_DISABLING, WIFI_AP_STATE_DISABLED, WIFI_AP_STATE_ENABLING, WIFI_AP_STATE_ENABLED, WIFI_AP_STATE_FAILED
     }

WifiApManager。 java

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.util.ArrayList;
import android.content.Context;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.util.Log;

public class WifiApManager {
private final WifiManager mWifiManager;

public WifiApManager(Context context) {
    mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
}



/**
 * Gets a list of the clients connected to the Hotspot, reachable timeout is 300
 * @param onlyReachables {@code false} if the list should contain unreachable (probably disconnected) clients, {@code true} otherwise
 * @return ArrayList of {@link ClientScanResult}
 */
public ArrayList<ClientScanResult> getClientList(boolean onlyReachables) {
    return getClientList(onlyReachables, 300);
}

/**
 * Gets a list of the clients connected to the Hotspot 
 * @param onlyReachables {@code false} if the list should contain unreachable (probably disconnected) clients, {@code true} otherwise
 * @param reachableTimeout Reachable Timout in miliseconds
 * @return ArrayList of {@link ClientScanResult}
 */
public ArrayList<ClientScanResult> getClientList(boolean onlyReachables, int reachableTimeout) {
    BufferedReader br = null;
    ArrayList<ClientScanResult> result = null;

    try {
        result = new ArrayList<ClientScanResult>();
        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("..:..:..:..:..:..")) {
                    boolean isReachable = InetAddress.getByName(splitted[0]).isReachable(reachableTimeout);

                    if (!onlyReachables || isReachable) {
                        result.add(new ClientScanResult(splitted[0], splitted[3], splitted[5], isReachable));
                    }
                }
            }
        }
    } catch (Exception e) {
        Log.e(this.getClass().toString(), e.getMessage());
    } finally {
        try {
            br.close();
        } catch (IOException e) {
            Log.e(this.getClass().toString(), e.getMessage());
        }
    }

    return result;
}
}

The following code will give you the ip adrress & other details of the wifi enabled devices connected to the the android hotspot device

Main.java

import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import com.whitebyte.hotspotclients.R;
import com.whitebyte.wifihotspotutils.ClientScanResult;
import com.whitebyte.wifihotspotutils.WifiApManager;

public class Main extends Activity {
      TextView textView1;
      WifiApManager wifiApManager;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    textView1 = (TextView) findViewById(R.id.textView1);
    wifiApManager = new WifiApManager(this);

    scan();
}

private void scan() {
    ArrayList<ClientScanResult> clients = wifiApManager.getClientList(false);

    textView1.append("Clients: \n");
    for (ClientScanResult clientScanResult : clients) {
        textView1.append("####################\n");
        textView1.append("IpAddr: " + clientScanResult.getIpAddr() + "\n");
        textView1.append("Device: " + clientScanResult.getDevice() + "\n");
        textView1.append("HWAddr: " + clientScanResult.getHWAddr() + "\n");
        textView1.append("isReachable: " + clientScanResult.isReachable() + "\n");
    }
}

ClientScanResult.java

public class ClientScanResult {

private String IpAddr;

private String HWAddr;

private String Device;

private boolean isReachable;

public ClientScanResult(String ipAddr, String hWAddr, String device, boolean isReachable) {
    super();
    IpAddr = ipAddr;
    HWAddr = hWAddr;
    Device = device;
    this.setReachable(isReachable);
}

public String getIpAddr() {
    return IpAddr;
}

public void setIpAddr(String ipAddr) {
    IpAddr = ipAddr;
}

public String getHWAddr() {
    return HWAddr;
}

public void setHWAddr(String hWAddr) {
    HWAddr = hWAddr;
}

public String getDevice() {
    return Device;
}

public void setDevice(String device) {
    Device = device;
}

public void setReachable(boolean isReachable) {
    this.isReachable = isReachable;
}

public boolean isReachable() {
    return isReachable;
}

}

WIFI_AP_STATE.java

     public enum WIFI_AP_STATE 
     {
        WIFI_AP_STATE_DISABLING, WIFI_AP_STATE_DISABLED, WIFI_AP_STATE_ENABLING, WIFI_AP_STATE_ENABLED, WIFI_AP_STATE_FAILED
     }

WifiApManager.java

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.util.ArrayList;
import android.content.Context;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.util.Log;

public class WifiApManager {
private final WifiManager mWifiManager;

public WifiApManager(Context context) {
    mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
}



/**
 * Gets a list of the clients connected to the Hotspot, reachable timeout is 300
 * @param onlyReachables {@code false} if the list should contain unreachable (probably disconnected) clients, {@code true} otherwise
 * @return ArrayList of {@link ClientScanResult}
 */
public ArrayList<ClientScanResult> getClientList(boolean onlyReachables) {
    return getClientList(onlyReachables, 300);
}

/**
 * Gets a list of the clients connected to the Hotspot 
 * @param onlyReachables {@code false} if the list should contain unreachable (probably disconnected) clients, {@code true} otherwise
 * @param reachableTimeout Reachable Timout in miliseconds
 * @return ArrayList of {@link ClientScanResult}
 */
public ArrayList<ClientScanResult> getClientList(boolean onlyReachables, int reachableTimeout) {
    BufferedReader br = null;
    ArrayList<ClientScanResult> result = null;

    try {
        result = new ArrayList<ClientScanResult>();
        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("..:..:..:..:..:..")) {
                    boolean isReachable = InetAddress.getByName(splitted[0]).isReachable(reachableTimeout);

                    if (!onlyReachables || isReachable) {
                        result.add(new ClientScanResult(splitted[0], splitted[3], splitted[5], isReachable));
                    }
                }
            }
        }
    } catch (Exception e) {
        Log.e(this.getClass().toString(), e.getMessage());
    } finally {
        try {
            br.close();
        } catch (IOException e) {
            Log.e(this.getClass().toString(), e.getMessage());
        }
    }

    return result;
}
}
忆依然 2024-12-26 01:13:30

检查 WLAN 接口的 arp 表。在命令行中 cat /proc/net/arp

Check your arp table for the wlan interface. cat /proc/net/arp at the command line.

国际总奸 2024-12-26 01:13:30

虽然给出了答案,但万一有人对直接答案感兴趣:

private static ArrayList<String> readArpCache()
   {
      ArrayList<String> ipList = new ArrayList<String>();
      BufferedReader br = null;
      try {
         br = new BufferedReader(new FileReader("/proc/net/arp"), 1024);
         String line;
         while ((line = br.readLine()) != null) {
            Log.d(TAG  ,line);

            String[] tokens = line.split(" +");
            if (tokens != null && tokens.length >= 4) {
               // verify format of MAC address
               String macAddress = tokens[3];
               if (macAddress.matches("..:..:..:..:..:..")) {
                  //Log.i(TAG, "MAC=" + macAddress + " IP=" + tokens[0] + " HW=" + tokens[1]);

                  // Ignore the entries with MAC-address "00:00:00:00:00:00"
                  if (!macAddress.equals("00:00:00:00:00:00")) {

                     String ipAddress = tokens[0];
                     ipList.add(ipAddress);

                     Log.i(TAG, macAddress + "; " + ipAddress);
                  }
               }
            }
         }
      } catch (Exception e) {
         e.printStackTrace();
      } finally {
         try {
            br.close();
         } catch (IOException e) {
            e.printStackTrace();
         }
      }

      return ipList;
   }

另外根据我的理解(我自己没有尝试过),如果您正在使用 aysntask 并且需要在工作线程上执行(不会在主线程上工作) ),也可以采用这个过程。要么使用方法查找热点接口,要么直接使用 _hotspotInterface 作为“wlan0”

try {
         InetAddress[] arr = InetAddress.getAllByName(_hotspotInterface);

      } catch (UnknownHostException e) {
         e.printStackTrace();
      } catch (Exception e) {
         e.printStackTrace();
      }

为了查找热点,我使用了这种方法(虽然不是很好的例子)

String _hotspotInterface = "";
     for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); )
             {
                NetworkInterface anInterface = en.nextElement();

                //look for 192.168.xx.xx first
                for (Enumeration<InetAddress> enumIpAddr = anInterface.getInetAddresses(); enumIpAddr.hasMoreElements(); )
                {
                   InetAddress inetAddress = enumIpAddr.nextElement();
                   String       hostAddress = inetAddress.getHostAddress();

                   if (hostAddress.startsWith("192.168."))
                   {
                      _hotspotInterface = anInterface.getName();
                   }
                }
}

Though the answer if given, but in case anyone is interested in direct answer:

private static ArrayList<String> readArpCache()
   {
      ArrayList<String> ipList = new ArrayList<String>();
      BufferedReader br = null;
      try {
         br = new BufferedReader(new FileReader("/proc/net/arp"), 1024);
         String line;
         while ((line = br.readLine()) != null) {
            Log.d(TAG  ,line);

            String[] tokens = line.split(" +");
            if (tokens != null && tokens.length >= 4) {
               // verify format of MAC address
               String macAddress = tokens[3];
               if (macAddress.matches("..:..:..:..:..:..")) {
                  //Log.i(TAG, "MAC=" + macAddress + " IP=" + tokens[0] + " HW=" + tokens[1]);

                  // Ignore the entries with MAC-address "00:00:00:00:00:00"
                  if (!macAddress.equals("00:00:00:00:00:00")) {

                     String ipAddress = tokens[0];
                     ipList.add(ipAddress);

                     Log.i(TAG, macAddress + "; " + ipAddress);
                  }
               }
            }
         }
      } catch (Exception e) {
         e.printStackTrace();
      } finally {
         try {
            br.close();
         } catch (IOException e) {
            e.printStackTrace();
         }
      }

      return ipList;
   }

Also as per my understanding (didn't try by myself), if you are using aysntask and need to do on worker thread(won't work on main thread), this process can also be used. Either use method to find hotspotinterface or directly use _hotspotInterface as "wlan0"

try {
         InetAddress[] arr = InetAddress.getAllByName(_hotspotInterface);

      } catch (UnknownHostException e) {
         e.printStackTrace();
      } catch (Exception e) {
         e.printStackTrace();
      }

To find hotspot I used this method(though not very good example)

String _hotspotInterface = "";
     for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); )
             {
                NetworkInterface anInterface = en.nextElement();

                //look for 192.168.xx.xx first
                for (Enumeration<InetAddress> enumIpAddr = anInterface.getInetAddresses(); enumIpAddr.hasMoreElements(); )
                {
                   InetAddress inetAddress = enumIpAddr.nextElement();
                   String       hostAddress = inetAddress.getHostAddress();

                   if (hostAddress.startsWith("192.168."))
                   {
                      _hotspotInterface = anInterface.getName();
                   }
                }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文