getComputerName method

  1. @visibleForTesting
String getComputerName()

Implementation

@visibleForTesting
String getComputerName() {
  // We call this a first time to get the length of the string in characters,
  // so we can allocate sufficient memory.
  final nSize = calloc<DWORD>();
  GetComputerNameEx(
      COMPUTER_NAME_FORMAT.ComputerNameDnsFullyQualified, nullptr, nSize);

  // Now allocate memory for a native string and call this a second time.
  final lpBuffer = wsalloc(nSize.value);
  try {
    final result = GetComputerNameEx(
        COMPUTER_NAME_FORMAT.ComputerNameDnsFullyQualified, lpBuffer, nSize);

    if (result != 0) {
      return lpBuffer.toDartString();
    } else {
      throw WindowsException(HRESULT_FROM_WIN32(GetLastError()));
    }
  } finally {
    free(lpBuffer);
    free(nSize);
  }
}