以编程方式连接WiFi会返回IP地址0.0.0.0

时间:2018-10-03 13:28:28

标签: android ip-address data-sharing wificonfiguration

我正在尝试通信两个设备以共享数据。一个设备充当server and creates hot spot,而另一设备充当client并连接到hot spot。我通过此代码以编程方式连接设备。

addNetwork(WifiMgr.createWifiCfg(ssid, password, sType));

public static WifiConfiguration createWifiCfg(String ssid, String password, int type){
    WifiConfiguration config = new WifiConfiguration();
    config.allowedAuthAlgorithms.clear();
    config.allowedGroupCiphers.clear();
    config.allowedKeyManagement.clear();
    config.allowedPairwiseCiphers.clear();
    config.allowedProtocols.clear();

    config.SSID = "\"" + ssid + "\"";

    if(type == WIFICIPHER_NOPASS){
        config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
    }else if(type == WIFICIPHER_WEP){
        config.hiddenSSID = true;
        config.wepKeys[0]= "\""+password+"\"";
        config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
        config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
        config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
        config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
        config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
        config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
        config.wepTxKeyIndex = 0;
    }else if(type == WIFICIPHER_WPA){
        config.preSharedKey = "\"" + password + "\"";
        config.status = WifiConfiguration.Status.ENABLED;
        config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
        config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
        config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
        config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
        config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
        config.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
    }

    return config;
}

 public boolean addNetwork(WifiConfiguration wf){

    disconnectCurrentNetwork();


    int netId = mWifiManager.addNetwork(wf);
    boolean enable = mWifiManager.enableNetwork(netId, true);
    return enable;
}

此代码成功连接了设备。在客户端进行通信,我需要服务器的IP address。以下代码返回IP address

private InetAddress getReceiverIP() {
    final String address = Formatter.formatIpAddress(dhcp.gateway);// gateway - default gateway IP address
    InetAddress receiverIP = null;
    try {
        receiverIP = InetAddress.getByName(address);
        if(mDebug)
            Log.i("FileSender","Receiver Name : " + address);
            Log.i("FileSender","Receiver IP : " + receiverIP.toString());


    } catch (Exception e) {
        if(mDebug)
        Log.e("FileSender","Cannot find receiver's IP. Error : " + e.toString());
    }

    return receiverIP;
}

问题是当我通过从设备设置屏幕手动完成连接到网络时,接收者的IP地址被接收为192.168.143.1并且成功共享了数据。但是,即使我在连接后仍以编程方式连接设备,它的IP地址仍为0.0.0.0,这就是为什么连接被拒绝的原因。 请告诉我我在做什么错。

0 个答案:

没有答案