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

前端 未结 6 1941
陌清茗
陌清茗 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:02

    I've been able to connect and send both ways in a WiFi direct network. All devices know the group owner's IP Address. We get the peer IP from a socket created for communication. Somehow getting the IP from the socket at the server side (at the group owner) did not work for me. So, I send the group owner the IP of the individual device from that device itself. To get the IP simply create a socket and bind it to any local port and get the address from this socket and send it over to the owner. I've used an UDP socket but it works well enough with TCP sockets.

    DatagramSocket socket=null;
         try {
            socket=new DatagramSocket();
            socket.connect((new InetSocketAddress(host, port)));
            String address=socket.getLocalAddress().getHostAddress();
            ByteBuffer bb=ByteBuffer.allocate(2+address.length());
            bb.putChar('I');
            bb.put(address.getBytes());
            DatagramPacket pkt=new DatagramPacket(bb.array(),2+address.length());
            socket.send(pkt);
            Log.d(WiFiDirectActivity.TAG,"address"+address+"dest"+host);
            Log.d(WiFiDirectActivity.TAG,"send");
        } catch (SocketException e) {
            Log.e(WiFiDirectActivity.TAG,"error socketException");
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (socket != null) {
                if (socket.isConnected()) {
                    socket.close();
                }
        }
    

    host is the address of the group owner we get from the connection info.

提交回复
热议问题