我用这个代码来更改wifi IP设置(IP地址和网关(
你可以在这里看到完整的代码:完整的类
WifiConfiguration wifiConf = null;
WifiManager manager = (WifiManager) getSystemService(MainActivity.WIFI_SERVICE);
WifiInfo connectionInfo = manager.getConnectionInfo();
List<WifiConfiguration> configuredNetworks = manager
.getConfiguredNetworks();
wifiConf = GetCurrentWifiConfiguration(manager);
setIpAssignment("STATIC", wifiConf);
setIpAddress(InetAddress.getByName("192.2.2.2"), 24, wifiConf);
setGateway(InetAddress.getByName("192.2.2.22"), wifiConf);
manager.updateNetwork(wifiConf);
manager.saveConfiguration();
功能:
public static void setIpAssignment(String assign , WifiConfiguration wifiConf)
throws SecurityException, IllegalArgumentException, NoSuchFieldException, IllegalAccessException{
setEnumField(wifiConf, assign, "ipAssignment");
}
public static void setIpAddress(InetAddress addr, int prefixLength, WifiConfiguration wifiConf)
throws SecurityException, IllegalArgumentException, NoSuchFieldException, IllegalAccessException,
NoSuchMethodException, ClassNotFoundException, InstantiationException, InvocationTargetException{
Object linkProperties = getField(wifiConf, "linkProperties");
if(linkProperties == null)return;
Class laClass = Class.forName("android.net.LinkAddress");
Constructor laConstructor = laClass.getConstructor(new Class[]{InetAddress.class, int.class});
Object linkAddress = laConstructor.newInstance(addr, prefixLength);
ArrayList mLinkAddresses = (ArrayList)getDeclaredField(linkProperties, "mLinkAddresses");
mLinkAddresses.clear();
mLinkAddresses.add(linkAddress);
}
public static void setGateway(InetAddress gateway, WifiConfiguration wifiConf)
throws SecurityException, IllegalArgumentException, NoSuchFieldException, IllegalAccessException,
ClassNotFoundException, NoSuchMethodException, InstantiationException, InvocationTargetException {
Object linkProperties = getField(wifiConf, "linkProperties");
if(linkProperties == null)return;
Class routeInfoClass = Class.forName("android.net.RouteInfo");
Constructor routeInfoConstructor = routeInfoClass.getConstructor(new Class[]{InetAddress.class});
Object routeInfo = routeInfoConstructor.newInstance(gateway);
ArrayList mRoutes = (ArrayList)getDeclaredField(linkProperties, "mRoutes");
mRoutes.clear();
mRoutes.add(routeInfo);
}
问题就在这里:
当您在Android设备中检查WiFi连接高级选项时,这些代码已成功更改IP地址和网关,但实际上并未设置该设置!!
我如何理解这一点:
首先我手动设置了一个假的IP地址和网关,修改网络>高级选项。 然后尝试使用 Chrome 打开一个网站,无法访问互联网,它有效。 然后我从代码中为连接的 ssid 设置了相同的 IP 地址和网关,但它不起作用,仍然可以访问互联网。
我从代码和手动使用相同的设置,但它不适用于代码。 我哪里做错了?
正如我所看到的,您可以更改设置并在设置视图上更改值,但设备上系统状态的实际更改并未发生。
您很可能没有权限使用程序更改 wifi 设置。
尝试添加以下内容:
ACCESS_WIFI_STATE
CHANGE_WIFI_STATE
ACCESS_NETWORK_STATE
有关更多信息,请参阅我对问题的评论。
如果您有唯一的 IP 地址,则可以添加任意数量的重复 SSID。
通俗地说,SSID只不过是对该特定网络的标识,以便为了简单起见将该网络与其他网络区分开来。定义该网络的是它的 IP 地址。如果 IP 地址之间存在冲突,那么这可能是一个真正的问题。
对于某些设备(如三星(,您需要选中显示打开的网络连接(如果可用(以查看打开的连接,对于某些设备,默认情况下显示。
例如:假设您有两个以SSID作为测试的网络。 Test1具有可供公众使用的开放连接,Test2供个人使用并已加密。您的移动设备将简单地连接到信号强度良好的网络。由于IP地址不同,因此不会有任何冲突,您可以进行浏览。
如果有任何冲突(相同的信号强度(,则设备将要求用户选择所需的网络或搜索新网络。
注意:-出于与财务相关的原因浏览开放网络会导致严重的安全威胁,浏览风险自负。
IP 地址有两个主要功能:主机或网络接口识别和位置寻址。它的作用特征如下:"名称表示我们所寻求的东西。地址指示它的位置。路线指示如何到达那里。
我可以给出的IP地址最简单的定义是-
IP地址充当您的住所地址,货物必须交付到该地址。如果您有两个相同的地址,那么货物将交付给谁。有关 IP 的更多详细信息,请阅读此内容
现在基本上我对你的问题的回答是:
您可以使用 ssid 大胆地添加多个设置,但安全级别不同
我准备的小演示:
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
connectToAP("12345", "12345");
WifiConfiguration wifiConf = null;
WifiManager wifiManager = (WifiManager) getSystemService(MainActivity.WIFI_SERVICE);
WifiInfo connectionInfo = wifiManager.getConnectionInfo();
List<WifiConfiguration> configuredNetworks = wifiManager
.getConfiguredNetworks();
for (WifiConfiguration conf : configuredNetworks) {
if (conf.networkId == 9) {
wifiConf = conf;
setWifiProxySettings(wifiConf);
try {
setIpAssignment("STATIC", wifiConf); // or "DHCP" for
// dynamic setting
setIpAddress(InetAddress.getByName("192.168.0.100"), 24,
wifiConf);
setGateway(InetAddress.getByName("4.4.4.4"), wifiConf);
setDNS(InetAddress.getByName("4.4.4.4"), wifiConf);
wifiManager.updateNetwork(wifiConf); // apply the setting
wifiManager.saveConfiguration(); // Save it
} catch (Exception e) {
e.printStackTrace();
}
break;
}
}
}
public static void setIpAssignment(String assign, WifiConfiguration wifiConf)
throws SecurityException, IllegalArgumentException,
NoSuchFieldException, IllegalAccessException {
setEnumField(wifiConf, assign, "ipAssignment");
}
public static void setEnumField(Object obj, String value, String name)
throws SecurityException, NoSuchFieldException,
IllegalArgumentException, IllegalAccessException {
Field f = obj.getClass().getField(name);
f.set(obj, Enum.valueOf((Class<Enum>) f.getType(), value));
}
public static void setIpAddress(InetAddress addr, int prefixLength,
WifiConfiguration wifiConf) throws SecurityException,
IllegalArgumentException, NoSuchFieldException,
IllegalAccessException, NoSuchMethodException,
ClassNotFoundException, InstantiationException,
InvocationTargetException {
Object linkProperties = getField(wifiConf, "linkProperties");
if (linkProperties == null)
return;
Class laClass = Class.forName("android.net.LinkAddress");
Constructor laConstructor = laClass.getConstructor(new Class[] {
InetAddress.class, int.class });
Object linkAddress = laConstructor.newInstance(addr, prefixLength);
ArrayList mLinkAddresses = (ArrayList) getDeclaredField(linkProperties,
"mLinkAddresses");
mLinkAddresses.clear();
mLinkAddresses.add(linkAddress);
}
public static void setGateway(InetAddress gateway,
WifiConfiguration wifiConf) throws SecurityException,
IllegalArgumentException, NoSuchFieldException,
IllegalAccessException, ClassNotFoundException,
NoSuchMethodException, InstantiationException,
InvocationTargetException {
Object linkProperties = getField(wifiConf, "linkProperties");
if (linkProperties == null)
return;
Class routeInfoClass = Class.forName("android.net.RouteInfo");
Constructor routeInfoConstructor = routeInfoClass
.getConstructor(new Class[] { InetAddress.class });
Object routeInfo = routeInfoConstructor.newInstance(gateway);
ArrayList mRoutes = (ArrayList) getDeclaredField(linkProperties,
"mRoutes");
mRoutes.clear();
mRoutes.add(routeInfo);
}
public static void setDNS(InetAddress dns, WifiConfiguration wifiConf)
throws SecurityException, IllegalArgumentException,
NoSuchFieldException, IllegalAccessException {
Object linkProperties = getField(wifiConf, "linkProperties");
if (linkProperties == null)
return;
ArrayList<InetAddress> mDnses = (ArrayList<InetAddress>) getDeclaredField(
linkProperties, "mDnses");
mDnses.clear(); // or add a new dns address , here I just want to
// replace DNS1
mDnses.add(dns);
}
public static Object getField(Object obj, String name)
throws SecurityException, NoSuchFieldException,
IllegalArgumentException, IllegalAccessException {
Field f = obj.getClass().getField(name);
Object out = f.get(obj);
return out;
}
public static Object getDeclaredField(Object obj, String name)
throws SecurityException, NoSuchFieldException,
IllegalArgumentException, IllegalAccessException {
Field f = obj.getClass().getDeclaredField(name);
f.setAccessible(true);
Object out = f.get(obj);
return out;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
String TAG = "wifi";
WifiManager wifiManager;
public void connectToAP(String ssid, String passkey) {
Log.i(TAG, "* connectToAP");
wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
WifiConfiguration wifiConfiguration = new WifiConfiguration();
String networkSSID = ssid;
String networkPass = passkey;
Log.d(TAG, "# password " + networkPass);
// for (ScanResult result : scanResultList) {
// if (result.SSID.equals(networkSSID)) {
if (true) {
// String securityMode = getScanResultSecurity(result);
String securityMode = "OPEN";
if (securityMode.equalsIgnoreCase("OPEN")) {
wifiConfiguration.SSID = """ + networkSSID + """;
wifiConfiguration.allowedKeyManagement
.set(WifiConfiguration.KeyMgmt.NONE);
int res = wifiManager.addNetwork(wifiConfiguration);
Log.d(TAG, "# add Network returned " + res);
boolean b = wifiManager.enableNetwork(res, true);
Log.d(TAG, "# enableNetwork returned " + b);
wifiManager.setWifiEnabled(true);
} else if (securityMode.equalsIgnoreCase("WEP")) {
wifiConfiguration.SSID = """ + networkSSID + """;
wifiConfiguration.wepKeys[0] = """ + networkPass + """;
wifiConfiguration.wepTxKeyIndex = 0;
wifiConfiguration.allowedKeyManagement
.set(WifiConfiguration.KeyMgmt.NONE);
wifiConfiguration.allowedGroupCiphers
.set(WifiConfiguration.GroupCipher.WEP40);
int res = wifiManager.addNetwork(wifiConfiguration);
Log.d(TAG, "### 1 ### add Network returned " + res);
boolean b = wifiManager.enableNetwork(res, true);
Log.d(TAG, "# enableNetwork returned " + b);
wifiManager.setWifiEnabled(true);
}
wifiConfiguration.SSID = """ + networkSSID + """;
wifiConfiguration.preSharedKey = """ + networkPass + """;
wifiConfiguration.hiddenSSID = true;
wifiConfiguration.status = WifiConfiguration.Status.ENABLED;
wifiConfiguration.allowedGroupCiphers
.set(WifiConfiguration.GroupCipher.TKIP);
wifiConfiguration.allowedGroupCiphers
.set(WifiConfiguration.GroupCipher.CCMP);
wifiConfiguration.allowedKeyManagement
.set(WifiConfiguration.KeyMgmt.WPA_PSK);
wifiConfiguration.allowedPairwiseCiphers
.set(WifiConfiguration.PairwiseCipher.TKIP);
wifiConfiguration.allowedPairwiseCiphers
.set(WifiConfiguration.PairwiseCipher.CCMP);
wifiConfiguration.allowedProtocols
.set(WifiConfiguration.Protocol.RSN);
wifiConfiguration.allowedProtocols
.set(WifiConfiguration.Protocol.WPA);
int res = wifiManager.addNetwork(wifiConfiguration);
Log.d(TAG, "### 2 ### add Network returned " + res);
wifiManager.enableNetwork(res, true);
boolean changeHappen = wifiManager.saveConfiguration();
if (res != -1 && changeHappen) {
Log.d(TAG, "### Change happen");
// AppStaticVar.connectedSsidName = networkSSID;
} else {
Log.d(TAG, "*** Change NOT happen");
}
wifiManager.setWifiEnabled(true);
}
// }
}
public String getScanResultSecurity(ScanResult scanResult) {
Log.i(TAG, "* getScanResultSecurity");
final String cap = scanResult.capabilities;
final String[] securityModes = { "WEP", "PSK", "EAP" };
for (int i = securityModes.length - 1; i >= 0; i--) {
if (cap.contains(securityModes[i])) {
return securityModes[i];
}
}
return "OPEN";
}
/* PROXY SETTINGS */
/*********************************************************************/
// public static Object getField(Object obj, String name)
// throws SecurityException, NoSuchFieldException,
// IllegalArgumentException, IllegalAccessException {
// Field f = obj.getClass().getField(name);
// Object out = f.get(obj);
// return out;
// }
//
// public static Object getDeclaredField(Object obj, String name)
// throws SecurityException, NoSuchFieldException,
// IllegalArgumentException, IllegalAccessException {
// Field f = obj.getClass().getDeclaredField(name);
// f.setAccessible(true);
// Object out = f.get(obj);
// return out;
// }
//
// public static void setEnumField(Object obj, String value, String name)
// throws SecurityException, NoSuchFieldException,
// IllegalArgumentException, IllegalAccessException {
// Field f = obj.getClass().getField(name);
// f.set(obj, Enum.valueOf((Class<Enum>) f.getType(), value));
// }
public static void setProxySettings(String assign,
WifiConfiguration wifiConf) throws SecurityException,
IllegalArgumentException, NoSuchFieldException,
IllegalAccessException {
setEnumField(wifiConf, assign, "proxySettings");
}
WifiConfiguration GetCurrentWifiConfiguration(WifiManager manager) {
if (!manager.isWifiEnabled())
return null;
List<WifiConfiguration> configurationList = manager
.getConfiguredNetworks();
WifiConfiguration configuration = null;
int cur = manager.getConnectionInfo().getNetworkId();
for (int i = 0; i < configurationList.size(); ++i) {
WifiConfiguration wifiConfiguration = configurationList.get(i);
if (wifiConfiguration.networkId == cur)
configuration = wifiConfiguration;
}
return configuration;
}
void setWifiProxySettings(WifiConfiguration config) {
if (null == config)
return;
try {
Object linkProperties = getField(config, "linkProperties");
if (null == linkProperties)
return;
Class proxyPropertiesClass = Class
.forName("android.net.ProxyProperties");
Class[] setHttpProxyParams = new Class[1];
setHttpProxyParams[0] = proxyPropertiesClass;
Class lpClass = Class.forName("android.net.LinkProperties");
Method setHttpProxy = lpClass.getDeclaredMethod("setHttpProxy",
setHttpProxyParams);
setHttpProxy.setAccessible(true);
// get ProxyProperties constructor
Class[] proxyPropertiesCtorParamTypes = new Class[3];
proxyPropertiesCtorParamTypes[0] = String.class;
proxyPropertiesCtorParamTypes[1] = int.class;
proxyPropertiesCtorParamTypes[2] = String.class;
Constructor proxyPropertiesCtor = proxyPropertiesClass
.getConstructor(proxyPropertiesCtorParamTypes);
// create the parameters for the constructor
Object[] proxyPropertiesCtorParams = new Object[3];
proxyPropertiesCtorParams[0] = "127.0.0.1";
proxyPropertiesCtorParams[1] = 8118;
proxyPropertiesCtorParams[2] = "example.com";
// create a new object using the params
Object proxySettings = proxyPropertiesCtor
.newInstance(proxyPropertiesCtorParams);
// pass the new object to setHttpProxy
Object[] params = new Object[1];
params[0] = proxySettings;
setHttpProxy.invoke(linkProperties, params);
setProxySettings("STATIC", config);
} catch (Exception e) {
}
}
void unsetWifiProxySettings() {
WifiManager manager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiConfiguration config = GetCurrentWifiConfiguration(manager);
if (null == config)
return;
try {
// get the link properties from the wifi configuration
Object linkProperties = getField(config, "linkProperties");
if (null == linkProperties)
return;
// get the setHttpProxy method for LinkProperties
Class proxyPropertiesClass = Class
.forName("android.net.ProxyProperties");
Class[] setHttpProxyParams = new Class[1];
setHttpProxyParams[0] = proxyPropertiesClass;
Class lpClass = Class.forName("android.net.LinkProperties");
Method setHttpProxy = lpClass.getDeclaredMethod("setHttpProxy",
setHttpProxyParams);
setHttpProxy.setAccessible(true);
// pass null as the proxy
Object[] params = new Object[1];
params[0] = null;
setHttpProxy.invoke(linkProperties, params);
setProxySettings("NONE", config);
// save the config
manager.updateNetwork(config);
manager.disconnect();
manager.reconnect();
} catch (Exception e) {
}
}
}
在上面的代码中,尝试使用以下命令运行相同的代码:
String securityMode = "OPEN";
String securityMode = "WEP";
一次一次:
观察:这两个设置都是以编程方式添加的,但由于两者都相互重叠,因此只能看到一次。但两者都存在。现在的问题是我怎么知道两者都存在?1. 运行上面的代码。2. 一次以 OPEN 作为安全级别,一次使用 WEP3.添加标签后,无线网络,并有忘记网络的选项。点击它4.您会观察到,尽管您删除了它,但它仍然存在:)5.因此,这两个设置都存在,但以编程方式重叠。
我对热点的分析:
我将 2 台设备作为具有相同 ssid 但安全级别不同的热点,我可以看到 2 个单独的 wifi,但问题是当以编程方式添加时,它会留在那里但重叠。
注意:手动或以编程方式添加相同的WIFI设置肯定会覆盖现有的WIFI设置,但即使有1个设置差异,它也可以工作。
mWifiManager.updateNetwork(selectWIfiConfi);
mWifiManager.saveConfiguration();
mWifiManager.setWifiEnabled(false);
mWifiManager.setWifiEnabled(true);
我重新打开wifi,它可以工作手机的版本4.2.2