Android 8.0 Tv 修改以太网ip地址 掩码 网关 DNS及DHCP和静态切换
16lz
2021-01-23
1.修改静态IP:
import android.net.IpConfiguration;import android.net.IpConfiguration.IpAssignment;import android.net.IpConfiguration.ProxySettings;import android.os.Environment;import android.util.Log;import android.util.SparseArray; import com.android.server.net.IpConfigStore; import java.net.InetAddress;//add by lvjiongimport android.net.NetworkUtils;import android.net.LinkAddress;import android.net.StaticIpConfiguration; private boolean setStaticIp(){ boolean isSuccessful = true; try { //每个IpConfiguration对象内部都包含了一个StaticIpConfiguration对象,对于DHCP方式来说这个对象赋为null StaticIpConfiguration staticIpConfiguration = new StaticIpConfiguration();//用于保存静态IP、dns、gateway、netMask相关参数配置 InetAddress mIpAddr = NetworkUtils.numericToInetAddress("192.168.50.239");//把192.168.1.1这种格式字符串转化为IP地址对象 String[] strs = "255.255.255.0".split("\\."); int count = 0; for(String str : strs){ if(str.equals("255")){ count++; } } int prefixLength = count*8; LinkAddress mIpAddress = new LinkAddress(mIpAddr,prefixLength);//prefixLength就是表示子网掩码字符有几个255,比如255.255.255.0的prefixLength为3 InetAddress mGateway = NetworkUtils.numericToInetAddress("192.168.50.255");//默认网关 ArrayList<InetAddress> mDnsServers = new ArrayList<InetAddress>();//DNS mDnsServers.add(NetworkUtils.numericToInetAddress("192.168.50.1")); //mDnsServers.add(NetworkUtils.numericToInetAddress(et_dns2.getText().toString())); staticIpConfiguration.ipAddress = mIpAddress; staticIpConfiguration.gateway = mGateway; staticIpConfiguration.dnsServers.addAll(mDnsServers); //ProxySettings为代理服务配置,主要有STATIC(手动代理)、PAC(自动代理)两种,NONE为不设置代理,UNASSIGNED为未配置代理(framework会使用NONE替代它) //ProxyInfo包含代理配置信息 IpConfiguration config = new IpConfiguration(IpConfiguration.IpAssignment.STATIC, IpConfiguration.ProxySettings.NONE, staticIpConfiguration, ProxyInfo.buildDirectProxy(null,0)); mEthernetManager.setConfiguration(config);//执行该方法后,系统会先通过EthernetConfigStore保存IP配置到data/misc/ethernet/ipconfig.txt,再更新以太网配置、通过EthernetNetworkFactory重启eth设备(最终通过NetworkManagementService来操作开启关闭设备、更新状态) //NetworkManagementService服务中提供了各种直接操作eth设备的API,如开关、列举、读写配置eth设备,都是通过发送指令实现与netd通信 //Netd 就是Network Daemon 的缩写,表示Network守护进程,Netd负责跟一些涉及网络的配置,操作,管理,查询等相关的功能实现 }catch (Exception e) { e.printStackTrace(); isSuccessful = false; } return isSuccessful; }
2.修改动态IP:
public void setMoveIp(){try {//对比STATIC,只需要把StaticIpConfiguration赋值为nullIpConfiguration config = new IpConfiguration(IpConfiguration.IpAssignment.DHCP, IpConfiguration.ProxySettings.NONE, null, ProxyInfo.buildDirectProxy(null,0));mEthManager.setConfiguration(config);}catch (Exception e) {e.printStackTrace();}}
更多相关文章
- Android得到SD卡文件夹大小以及删除文件夹操作
- android-数据库操作实例,留着以后用
- Android 添加桌面快捷方式操作
- Android中使用Parcelable传递对象,createFromParcel中对象的赋值
- Activity之间传递类对象