在 C# 中通过 WSOCK32.DLL 获取计算机名称

Get computer name via WSOCK32.DLL in C#

我正在将一些 VB6 代码迁移到 C# (.NET 4.5.2) 并卡在一段代码中,该代码从 WSOCK32.DLL 调用 gethostname 方法显然检索 计算机名。到目前为止我发现的所有代码示例都指向 this code。由于我无法在 C# 中成功 PInvoke gethostname 方法,我不禁要问是否有替代方法。

这个

[DllImport("WSOCK32.DLL", SetLastError = true)]
internal static extern long gethostname(string name, int nameLen);


string host = string.Empty;
var res = gethostname(host, 256);

失败并出现以下错误:

运行时遇到致命错误。错误地址位于线程 0xd88 上的 0x6a13a84e。错误代码是 0xc0000005。此错误可能是 CLR 中的错​​误,或者是用户代码的不安全或不可验证部分中的错误。此错误的常见来源包括 COM 互操作或 PInvoke 的用户编组错误,这可能会损坏堆栈。

我还阅读了有关使用 System.Environment.MachineName 或 "COMPUTERNAME" 环境变量的信息,但我感兴趣的是结果与 gethostname 方法 returns 有何不同。

我有什么选择?

您不能改为发送 zero-length immutable C# string and expect it to get turned into something new. You are probably experiencing a buffer overflow. You need to use a StringBuilder

[DllImport("WSOCK32.DLL", SetLastError = true)]
internal static extern long gethostname(StringBuilder name, int nameLen);

var builder = new StringBuilder(256);
var res = gethostname(builder, 256);
string host = builder.ToString();

更多信息在这里:

此外,确实没有理由使用那个非常古老的 DLL 函数来获取本地计算机的名称。只需使用 System.Environment.MachineName 即可。