在Windows Subsystem for Linux (WSL) 中,本地主机的 IP 地址与 Windows 主机的 IP 地址是不同的。这是由于 WSL 使用了虚拟网络适配器。
如果你需要在 WSL 中获取本地主机的 IP 地址,可以使用以下方法:
方法一:使用 ifconfig 命令
ifconfig eth0
注意:WSL 中的网络适配器通常被分配为 eth0。方法二:使用 ip addr 命令
ip addr show eth0
注意:WSL 中的网络适配器通常被分配为 eth0。方法三:使用 PowerShell
wsl hostname -I
如果你需要在代码中获取本地主机的 IP 地址,可以使用以下代码示例:
Python:
import subprocess
def get_local_ip():
result = subprocess.run(['wsl', 'hostname', '-I'], capture_output=True, text=True)
ip_addresses = result.stdout.strip().split()
return ip_addresses[0] if ip_addresses else None
print(get_local_ip())
JavaScript (Node.js):
const { execSync } = require('child_process');
function getLocalIp() {
const command = 'wsl hostname -I';
const ipAddresses = execSync(command).toString().trim().split(' ');
return ipAddresses[0] || null;
}
console.log(getLocalIp());
请注意,以上的示例代码假设你已经安装了 WSL 并且网络适配器的名称为 eth0。如果你在 WSL 中使用的是其他网络适配器名称,需要相应地修改代码中的网络适配器名称。