android - 如何获取Android中WiFi-Direct(WiFi-P2P)对等设备的IP地址?

标签 android wifi-direct

我正在尝试在 Android 中实现 WiFi-Direct(WiFi-P2P)。我引用了 samples\android-19\legacy\WiFiDirectDemo 中的示例代码。

我在 phone-A 上安装了 WiFiDirectDemo.apk 并运行它。 phone-BAndroid Setting 中打开 WiFi-Direct(WiFi-P2P)

phone-A连接到phone-B后,在phone-A上显示如下信息。

enter image description here

代码如下:

@Override
    public void onConnectionInfoAvailable(final WifiP2pInfo info) {
        Log.d(WifiP2P.TAG, "onConnectionInfoAvailable----------- " + info);
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
        this.info = info;
        this.getView().setVisibility(View.VISIBLE);

        // The owner IP is now known.
        TextView view = (TextView) mContentView.findViewById(R.id.group_owner);
        view.setText(getResources().getString(R.string.group_owner_text)
                + ((info.isGroupOwner == true) ? getResources().getString(R.string.yes)
                        : getResources().getString(R.string.no)));

        // InetAddress from WifiP2pInfo struct.
        view = (TextView) mContentView.findViewById(R.id.device_info);
        view.setText("Group Owner IP - " + info.groupOwnerAddress.getHostAddress());

        // After the group negotiation, we assign the group owner as the file
        // server. The file server is single threaded, single connection server
        // socket.
        if (info.groupFormed && info.isGroupOwner) {
            new FileServerAsyncTask(getActivity(), mContentView.findViewById(R.id.status_text))
                    .execute();
        } else if (info.groupFormed) {
            // The other device acts as the client. In this case, we enable the
            // get file button.
            mContentView.findViewById(R.id.btn_start_client).setVisibility(View.VISIBLE);
            ((TextView) mContentView.findViewById(R.id.status_text)).setText(getResources()
                    .getString(R.string.client_text));
        }

        // hide the connect button
        mContentView.findViewById(R.id.btn_connect).setVisibility(View.GONE);                 
    }

phone-AGroup Owner。我想将 TCP 数据从 phone-A 发送到 phone-B

<强>1。如何获取 phone-B 的 IP 地址。 ?

<强>2。 Group Owner IP是指Phone-A

IP地址

最佳答案

要获取 IP 地址,您必须使用以下方法。

  public static String getIpAddress() {
    try {
        List<NetworkInterface> interfaces = Collections
                .list(NetworkInterface.getNetworkInterfaces());
        /*
         * for (NetworkInterface networkInterface : interfaces) { Log.v(TAG,
         * "interface name " + networkInterface.getName() + "mac = " +
         * getMACAddress(networkInterface.getName())); }
         */

        for (NetworkInterface intf : interfaces) {
            if (!getMACAddress(intf.getName()).equalsIgnoreCase(
                    Globals.thisDeviceAddress)) {
                // Log.v(TAG, "ignore the interface " + intf.getName());
                // continue;
            }
            if (!intf.getName().contains("p2p"))
                continue;

            Log.v(TAG,
                    intf.getName() + "   " + getMACAddress(intf.getName()));

            List<InetAddress> addrs = Collections.list(intf
                    .getInetAddresses());

            for (InetAddress addr : addrs) {
                // Log.v(TAG, "inside");

                if (!addr.isLoopbackAddress()) {
                    // Log.v(TAG, "isnt loopback");
                    String sAddr = addr.getHostAddress().toUpperCase();
                    Log.v(TAG, "ip=" + sAddr);

                    boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr);

                    if (isIPv4) {
                        if (sAddr.contains("192.168.49.")) {
                            Log.v(TAG, "ip = " + sAddr);
                            return sAddr;
                        }
                    }

                }

            }
        }

    } catch (Exception ex) {
        Log.v(TAG, "error in parsing");
    } // for now eat exceptions
    Log.v(TAG, "returning empty ip address");
    return "";
}

public static String getMACAddress(String interfaceName) {
        try {
            List<NetworkInterface> interfaces = Collections
                    .list(NetworkInterface.getNetworkInterfaces());

            for (NetworkInterface intf : interfaces) {
                if (interfaceName != null) {
                    if (!intf.getName().equalsIgnoreCase(interfaceName))
                        continue;
                }
                byte[] mac = intf.getHardwareAddress();
                if (mac == null)
                    return "";
                StringBuilder buf = new StringBuilder();
                for (int idx = 0; idx < mac.length; idx++)
                    buf.append(String.format("%02X:", mac[idx]));
                if (buf.length() > 0)
                    buf.deleteCharAt(buf.length() - 1);
                return buf.toString();
            }
        } catch (Exception ex) {
        } // for now eat exceptions
        return "";
        /*
         * try { // this is so Linux hack return
         * loadFileAsString("/sys/class/net/" +interfaceName +
         * "/address").toUpperCase().trim(); } catch (IOException ex) { return
         * null; }
         */
    }

关于android - 如何获取Android中WiFi-Direct(WiFi-P2P)对等设备的IP地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26373862/

相关文章:

android - 如何处理 TextView 和 Layout 之间的宽度大小滞后?

android - R.java 未生成

android - 改造 SocketTimeoutException - 上传图像

android - Raspberry Pi 中 Wifi 直连几秒后自动断开连接

android - 使用 Android 应用程序检查 Miracast 兼容设备

android获取变量到自定义 View 的构造函数

android - 使用自定义 ErrorHandler 时改造不会触发 onError

java - Android 不支持 wifi p2p (wifidirect)

c# - uwp 中的 Wi-Fi 直连

android-intent - 在android wifi direct中设置组所有者