新手。请问:怎么获取以太网IPv4的地址和DNS?
自己写的代码如下 :运行后DNS服务器出来的总是IPV6的格式,请问各位大佬应该怎么改?
private void button1_Click(object sender, EventArgs e)
{
NetworkInterface[] accard = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface adapter in accard)
{
bool pd1 = (adapter.NetworkInterfaceType == NetworkInterfaceType.Ethernet);//判断是否连接以太网
if (pd1)
{
IPInterfaceProperties ip = adapter.GetIPProperties();//IP配置信息
UnicastIPAddressInformationCollection ipCollection = ip.UnicastAddresses;
foreach (UnicastIPAddressInformation ipadd in ipCollection)
{
if (ipadd.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
IPAddress.Text = ipadd.Address.ToString();
}
if (ip.GatewayAddresses.Count > 0)
{
Gateway.Text = ip.GatewayAddresses[0].Address.ToString();//获取默认网关
}
int DNSCount = ip.DnsAddresses.Count;
if (DNSCount > 0)
{
try
{
DNSserver.Text = ip.DnsAddresses[0].ToString();//获取首选DNS地址和备选DNS地址
secDNS.Text = ip.DnsAddresses[0].ToString();
}
catch (Exception ex)
{
throw ex;
}
}
}
}
}