You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Electron中获取计算机所连接的域名

在Electron中获取计算机连接的域名

你提到在C#中通过IPGlobalProperties.DomainName可轻松获取计算机连接的域名,但Electron无直接对应API,当前通过用户名拆分的方法仅在域账户登录场景有效,无法覆盖所有情况。以下是跨平台解决方案:

实现思路

Electron基于Node.js,可通过调用系统原生命令获取网络域名,不同平台使用对应命令解析结果:

  • Windows:执行net config workstation提取域名信息
  • Linux:执行hostname -d获取域名
  • macOS:优先用hostname -d,失败则通过scutil解析主机名提取域名
  • 兜底方案:保留原用户名拆分逻辑,兼容域账户场景

代码实现

const { execSync } = require('child_process');
const os = require('os');

function getComputerDomain() {
  let domain = null;
  const platform = os.platform();

  try {
    switch (platform) {
      case 'win32':
        const winOutput = execSync('net config workstation', { encoding: 'utf8' });
        const winDomainMatch = winOutput.match(/Domain\s*:\s*(.*)/);
        domain = winDomainMatch ? winDomainMatch[1].trim() : null;
        break;
      case 'linux':
        domain = execSync('hostname -d', { encoding: 'utf8' }).trim();
        break;
      case 'darwin':
        try {
          domain = execSync('hostname -d', { encoding: 'utf8' }).trim();
        } catch (e) {
          const hostName = execSync('scutil --get HostName', { encoding: 'utf8' }).trim();
          const domainParts = hostName.split('.');
          domain = domainParts.length > 1 ? domainParts.slice(1).join('.') : null;
        }
        break;
    }
  } catch (error) {
    console.error('获取域名失败:', error);
  }

  // 兜底:从用户名拆分域名(仅适用于域账户登录场景)
  if (!domain) {
    const username = os.userInfo().username;
    const domainArray = username.split('\\');
    domain = domainArray.length > 1 ? domainArray[0] : null;
  }

  return domain;
}

// 调用示例
console.log('计算机域名:', getComputerDomain());

说明

  • 该方法直接调用系统命令获取网络层面的域名,比仅从用户名拆分更准确,覆盖设备已加入域但使用本地账户登录的场景
  • 打包后的Electron应用通常无需额外权限即可执行这些系统命令,除非是受严格限制的系统环境

内容的提问来源于stack exchange,提问作者Konda Reddy Yakkanti

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 22:43:08