How to get each device's IP address in Wi-Fi Direct scenario?

前端 未结 6 1942
陌清茗
陌清茗 2020-11-28 06:21

Starting from ICS, Wi-Fi Direct is introduced. Normally, we use the WifiP2pManager class to operate on Wi-Fi Direct, but it seems that it can only retrieve the

6条回答
  •  囚心锁ツ
    2020-11-28 07:05

    I have another approach !

    When you create the connection between the 2 (or more) devices, you can't set who is the owner and who is (are) the clients.

    The only information that you have about that is when the BroadCast receiver is connected, you receive an object "WifiP2pInfo". This object contain 2 interesting infos :

    • The owner ip address (mWifiP2PInfo.groupOwnerAddress). This string start by "/". Don't forget to remove it ! ;)
    • if you are the owner or not (mWifiP2PInfo.isGroupOwner)

    From that you have all that you need !

    If you are the groupOwner => Listen for a connection

    Else create a connection to the owner with the ip address.

    if (mWifiP2PInfo.isGroupOwner) {
        serverSocket = new ServerSocket(port);
        socket = serverSocket.accept();
    } else {
        // If the client is not listening when the server create the connection, the connection is not established => Try again
        int retry = 10;
    
        socket = new Socket();
        socket.bind(null);
        do {
            socket.connect((new InetSocketAddress(mWifiP2PInfo.groupOwnerAddress, port)), 500);
            retry--;
        } while (!socket.isConnected() && retry > 0);
    }
    

    Hop it can help you !!!

提交回复
热议问题