对几个IP地址集合的定义:
privateList
privateList
privateList
privateList
比较简单的方式是借助C#已封装好的类来进行操作:
this._hostName = Dns.GetHostName();
IPHostEntry ipHostEntry=Dns.GetHostByName(this._hostName);
this._localAddressFamily.AddRange(ipHostEntry.AddressList);
// 至此 ipHostEntry.AddressList就是IP地址的集合
NetworkInterface[] adapters=NetworkInterface.GetAllNetworkInterfaces();
// 至此 adapters保存了本机所有的网卡适配器信息
NetworkInterface属性如下:
foreach (NetworkInterface ni in adapters) {
IPInterfaceProperties ipProperties =ni.GetIPProperties();
UnicastIPAddressInformation curIP =ipProperties.UnicastAddresses[0];
this._localAddressFamily.Add(curIP.Address);// 添加IP地址
this._subNetAddressFamily.Add(curIP.IPv4Mask);// 添加子网掩码
this._defaultIPGateway.Add(ipProperties.GatewayAddresses[0].Address);//添加默认网关
}
//============================我 是 分 割 线 =============================================
另外,还可以通过WMI来获得需要的信息
ManagementClass mc = newManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection nics =mc.GetInstances();
foreach (ManagementObject nic in nics) {
if(Convert.ToBoolean(nic["ipEnabled"]) == true) {
Array ips = nic["IPAddress"] as String[];
Array subnets = nic["IPSubnet"] as String[];
Array gateways =nic["DefaultIPGateway"] as String[];
IPAddress curIP, curSubnet, curGateway;
if (ips != null && ips.Length > 0) {
curIP = IPAddress.Parse(ips.GetValue(ips.Length - 1));
this._localAddressFamily.Add(curIP);
}
if (subnets != null && subnets.Length > 0) {
curSubnet = IPAddress.Parse(subnets.GetValue(0));
this._subNetAddressFamily.Add(curSubnet);
}
if (gateways != null && gateways.Length > 0) {
curGateway =IPAddress.Parse(gateways.GetValue(0));
this._defaultIPGateway.Add(curGateway);
}
if (curIP != null && curSubnet != null) {
byte[] IPAddressByte = curIP.GetAddressBytes();
byte[] IPSubnetByte = curSubnet.GetAddressBytes();
StringBuilder broadcast = new StringBuilder();
for (int i = 0; i < 4; i++) {
broadcast.Append(IPAddressByte[i] | (~IPSubnetByte[i] & 255));
if (i != 3) {
broadcast.Append(".");
}
}
this._broadcastFamily.Add(IPAddress.Parse(broadcast.ToString()));
}
}
}