Merge pull request #143 from sssir/master

修复部分linux平台下获取ip出错问题
This commit is contained in:
Lewis Zou
2019-09-27 08:56:39 +08:00
committed by GitHub
2 changed files with 29 additions and 7 deletions
+1 -7
View File
@@ -68,13 +68,7 @@ namespace DotnetSpider.Common
TotalMemory = (int) (infoDic["MemTotal:"] / 1024);
}
var networkInterface = NetworkInterface.GetAllNetworkInterfaces()
.First(i => i.NetworkInterfaceType == NetworkInterfaceType.Ethernet ||
i.NetworkInterfaceType == NetworkInterfaceType.Wireless80211);
var unicastAddresses = networkInterface.GetIPProperties().UnicastAddresses;
IpAddress = unicastAddresses.First(a =>
a.IPv4Mask.ToString() != "255.255.255.255" && a.Address.AddressFamily == AddressFamily.InterNetwork)
.Address.ToString();
IpAddress = NetworkHelper.CurrentIpAddress();
OsDescription = $"{Environment.OSVersion.Platform} {Environment.OSVersion.Version}";
}
+28
View File
@@ -0,0 +1,28 @@
using System;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
namespace DotnetSpider.Common
{
public static class NetworkHelper
{
public static string CurrentIpAddress()
{
var networkInterfaces = NetworkInterface.GetAllNetworkInterfaces()
.Where(i => i.NetworkInterfaceType == NetworkInterfaceType.Ethernet ||
i.NetworkInterfaceType == NetworkInterfaceType.Wireless80211);
var unicastAddresses = networkInterfaces
.Select(i => i.GetIPProperties())
.SelectMany(p => p.UnicastAddresses);
var addressInfo = unicastAddresses
.Where(a => a.IPv4Mask.ToString() != "255.255.255.255" &&
a.Address.AddressFamily == AddressFamily.InterNetwork &&
!IPAddress.IsLoopback(a.Address))
.FirstOrDefault();
var ipAddress = addressInfo?.Address.ToString() ?? "127.0.0.1";
return ipAddress;
}
}
}