有时候不想读取配置文件来进行网络监听,默认把本级所有IP地址监听一遍,这个时候就需要获取本级所有IP地址。
如下:
string name = Dns.GetHostName();
IPAddress[] ipadrlist = Dns.GetHostAddresses(name);
try
{
foreach (IPAddress ipa in ipadrlist)
{
if (ipa.AddressFamily == AddressFamily.InterNetwork)
{
Console.WriteLine(ipa.ToString());
}
}
}
catch(Exception ex)
{
Console.WriteLine("{0}", ex.Message);
}
*************************************************上面的存在一个很严重的问题,在centos7下面无法获取到IP地址******
修改一下代码
var Ani = NetworkInterface.GetAllNetworkInterfaces();
foreach(var ni in Ani)
{
var ua =ni.GetIPProperties().UnicastAddresses.ToArray();
foreach(var va in ua)
{
if(va.Address.AddressFamily == AddressFamily.InterNetwork)
{
Console.WriteLine(va.Address.ToString());
}
}
}