dotnet / dotnet/runtime

`Environment.MachineName` has inconsistent semantics across platforms

Open
#122,077 9 comments 0 reactions 0 assignees View on GitHub
area-System.Runtime
Dominant language
C#
Stars
18.3k
Forks
5.6k
PR merge metrics
PR metrics pending

Description

### Description

[Documentation](https://learn.microsoft.com/en-us/dotnet/api/system.environment.machinename?view=net-10.0) for `Environment.MachineName` says:

> The name of this computer is established at system startup when the name is read from the registry

Checking the code we see that the call is simply forwarded to [GetComputerName](https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-getcomputernamea), which says:

> Retrieves the NetBIOS name of the local computer. This name is established at system startup, when the system reads it from the registry. GetComputerName retrieves only the NetBIOS name of the local computer. To retrieve the DNS host name, DNS domain name, or the fully qualified DNS name, call...

And

> The GetComputerName function retrieves the NetBIOS name established at system startup. Name changes made by [...] do not take effect until the user restarts the computer.

The PAL for Unix calls `gethostname` whose behaviour does _not_ correspond with the documentation. The returned value can change during the lifetime of the program.

On macOS, when connected over a VPN (for example) and without explicitly configuring the hostname with `sethostname` it's highly possible for the system to get an (invalid) hostname via DNS.

The proper value should be static, and likely reflect what is configured in the system's "Sharing" panel under "Local hostname". Ergo it would make more sense to query this from the System Configuration framework (e.g. `SCDynamicStoreCopyLocalHostName`). This would more closely reflect the results for Windows and the documentation.

### Reproduction Steps

Query `Environment.MachineName` on macOS and observe it returns the result of `sethostname` rather than a static value, as per the documentation.

### Expected behavior

`Environment.MachineName` should return the machine name, not its DNS host name; and it should be a static value as specified by the documentation.

### Actual behavior

`Environment.MachineName` on macOS returns a non-static value that can be configured with `sethostname`.

### Regression?

_No response_

### Known Workarounds

_No response_

### Configuration

.NET 10, macOS 26, arm64. The issue is not specific to this configuration.

### Other information

_No response_

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.