Q:

Get computer name via WSOCK32.DLL in C#

I am migrating some VB6 code to C# (.NET 4.5.2) and got stuck into a piece of code that is calling the gethostname method from the WSOCK32.DLL to apparently retrieve the computer name. All the code samples that I have found so far point to 
this code. And since I haven't been able to successfully PInvoke the gethostname method in C#, I can't help asking if is there an alternative to it. 
This
[DllImport("WSOCK32.DLL", SetLastError = true)]
internal static extern long gethostname(string name, int nameLen);

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

fails with the following error:
The runtime has encountered a fatal error. The address of the error was at 0x6a13a84e, on thread 0xd88. The error code is 0xc0000005. This error may be a bug in the CLR or in the unsafe or non-verifiable portions of user code. Common sources of this bug include user marshaling errors for COM-interop or PInvoke, which may corrupt the stack.
I also read about using System.Environment.MachineName or the "COMPUTERNAME" environment variable, but I am interested in how the result differs than what gethostname method returns. 
What options do I have?

I am developing on a 64bit system but I don't know if/how this affects working with WSOCK32.DLL since I found no documentation about it.

A:

You cannot send an 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 instead:
[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();

More info here:

Passing StringBuilder to PInvoke function
C# PInvoke out strings declaration
http://pinvoke.net/default.aspx/ws2_32/gethostname.html

Also, there is really no reason for using that really old DLL function to get the name of the local computer. Just use System.Environment.MachineName instead.

