(c#) 关于本地网络的IP地址的一些事

1、不通过Win32_NetworkAdapterConfiguration获取本地连接的IP地址

代码如下:(需引用using System.Net.NetworkInformation

//IP地址获取
string get = "";
NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface ni in interfaces)
{
	if (ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
	{
		foreach (UnicastIPAddressInformation ips in
		ni.GetIPProperties().UnicastAddresses)
		{
			if (ips.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                        {
                            get = ips.Address.ToString().Trim();  //遍历到最后就是本地网络(以太网)
			}
		}
	}
}



2、 C#修改IP地址、子网掩码以及默认网关的方法

代码如下:(需引用usingSystem.Management;

ManagementBaseObject inPar = null;
ManagementBaseObject outPar = null;
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
foreach (ManagementObject mo in moc)
{
//以下这句话是修改特定的网卡
if ((bool)mo["IPEnabled"] && (mo["IPAddress"] as String[])[0].ToString().Trim().Equals(ip))
{
	//设置ip地址和子网掩码 
	inPar = mo.GetMethodParameters("EnableStatic");
	inPar["IPAddress"] = new string[] { nip };       //远程IP地址
	inPar["SubnetMask"] = new string[] { nziwang };    //子网掩码
	outPar = mo.InvokeMethod("EnableStatic", inPar, null);

	//设置网关地址 
	inPar = mo.GetMethodParameters("SetGateways");
	inPar["DefaultIPGateway"] = new string[] { nwangguan }; //默认网关
	outPar = mo.InvokeMethod("SetGateways", inPar, null);
}
}




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值