C# 获取本机网络信息
IP MAC DNS 等信息获取
private void GetLocalInfo()
{
textBlock1.Text = "";
StringBuilder sb = new StringBuilder();
NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
//sb.AppendLine("适配器个数:" + adapters.Length);
foreach (NetworkInterface adapter in adapters)
{
if (adapter.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
{
//显示网络适配器描述信息、名称、类型、速度、MAC地址
sb.AppendLine("名称:" + adapter.Name);
sb.AppendLine("描述:" + adapter.Description);
//sb.AppendLine("类型:" + adapter.NetworkInterfaceType);
sb.AppendLine("链接速度(接收/传输):" + adapter.Speed / 1000 / 1000 + "/" + adapter.Speed / 1000 / 1000 + "(Mbps)");
byte[] macBytes = adapter.GetPhysicalAddress().GetAddressBytes();
sb.AppendLine("物理地址(MAC):" + BitConverter.ToString(macBytes));
//获取IPInterfaceProperties实例
IPInterfaceProperties adapterProperties = adapter.GetIPProperties();
//获取该IP对象的网关
GatewayIPAddressInformationCollection gateways = adapterProperties.GatewayAddresses;
foreach (var gateWay in gateways)
{
//如果能够Ping通网关
if (IsPingIP(gateWay.Address.ToString()))
{
//得到网关地址
sb.AppendLine("默认网关:" + gateWay.Address.ToString());
//跳出循环
break;
}
}
//获取并显示DNS服务器IP地址信息
IPAddressCollection dnsServers = adapterProperties.DnsAddresses;
if (dnsServers.Count > 0)
{
StringBuilder dnsinfo = new StringBuilder();
foreach (IPAddress dns in dnsServers)
{
dnsinfo.Append(dns + " ");
}
sb.AppendLine("DNS服务器:" + dnsinfo.ToString().Trim());
}
}
}
string hostName = Dns.GetHostName();
IPHostEntry me = Dns.GetHostEntry(hostName);
foreach (IPAddress ip in me.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
sb.AppendLine("IPv4 地址:" + ip.ToString());
}
else if (ip.AddressFamily == AddressFamily.InterNetworkV6)
{
sb.AppendLine("IPv6 地址:" + ip.ToString());
}
else
{
sb.AppendLine("其他:" + ip.ToString());
}
}
IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties();
IPGlobalStatistics ipstat = properties.GetIPv4GlobalStatistics();
sb.AppendLine("本机注册域名 : " + properties.DomainName);
sb.AppendLine("接收数据包数 : " + ipstat.ReceivedPackets);
sb.AppendLine("转发数据包数 : " + ipstat.ReceivedPacketsForwarded);
sb.AppendLine("传送数据包数 : " + ipstat.ReceivedPacketsDelivered);
sb.AppendLine("丢弃数据包数 : " + ipstat.ReceivedPacketsDiscarded);
textBlock1.Text = sb.ToString();
}