且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 Windows 10 通用应用程序上的 C# 中获取本地主机名

更新时间:2023-11-19 21:07:34

您需要使用 NetworkInformation.GetHostNames.

You need to use NetworkInformation.GetHostNames.

var hostNames = Windows.Networking.Connectivity.NetworkInformation.GetHostNames();

但是注意这个方法会返回多个HostName.

But note that this method will return multiple HostNames.

就我而言,它返回四个 HostName,其中 DisplayNameMyComputerNameMyComputerName.local加上两个 IP 地址.

In my case, it returns four HostNames of which DisplayNames are MyComputerName, MyComputerName.local plus two IP addresses.

所以我想这样做可能是安全的 -

So I guess it's probably safe to do -

using Windows.Networking;
using Windows.Networking.Connectivity;


var hostNames = NetworkInformation.GetHostNames();
var hostName = hostNames.FirstOrDefault(name => name.Type == HostNameType.DomainName)?.DisplayName ?? "???";