C# - .NET Core中如何使用Dns.GetHostEntry(uri.Host)?

3

我可以使用Dns.GetHostEntry("google.com")获取"google.com"这个URI的IP地址,例如:

        var ip = Dns.GetHostEntry("google.com");
        Console.WriteLine(ip.AddressList.FirstOrDefault().ToString());
        Console.ReadKey();

这段代码在 .net framework 中可以正常工作,但我有一个跨平台项目,需要在 .net core 1.1 和 .net standard 1.6 中使用此代码。然而,.net core 和 standard 版本不支持 System.Net.Dns.GetHostEntry 方法。那么,在 .net core 和 standard 中,如何通过 Dns 获取主机名的服务器 IP 地址呢?

1个回答

4

经过再次检查,我发现在 .net standard 和 .net core 中有 Dns.GetHostEntryAsync 方法,因此我将我的代码更改为支持 .net4、.net45、.net core 和 .net standard:

#if (NETSTANDARD1_6 || NETCOREAPP1_1)
            IPHostEntry Host = await Dns.GetHostEntryAsync(uri.Host);
#else
            IPHostEntry Host = Dns.GetHostEntry(uri.Host);
#endif

为什么要使用 NETSTANDARD1_6 || NETCOREAPP1_1,而不是只用 NETSTANDARD1_6? 如果这是一个库,你只需要针对 netstandard 进行目标设置,而不是 netcoreapp(或者我想知道为什么)。 - Treziac
因为如果我将来在我的项目中使用 Microsoft.NETCore.CoreCLR 包,.net standard 就不支持该库,而我在我的项目中同时使用 .net core 和 .net standard,这只是为了后者。 - Ali Yousefi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接