【发布时间】:2016-11-28 08:58:52
【问题描述】:
我在 Windows 上工作,想获取网络接口名称,无论是 eth0、eth1、eth2 等等等。我编写了 java 程序,通过传递主机/计算机名称,我可以找到 ip 地址,然后根据 ip address 我可以找到网络接口名称。代码如下:
public static String getNetworkInterface() {
try {
String computerHostName = "dummy";
if(!computerHostName.equals("Unknown Computer")) {
InetAddress address = InetAddress.getByName(computerHostName);
return NetworkInterface.getByInetAddress(address).getName();
}
else {
return null;
}
}
catch (SocketException e) {
e.printStackTrace();
}
catch (UnknownHostException e) {
e.printStackTrace();
}
return null;
}
上述方法返回的值类似于 eth0/eth1/eth2 等。
我想在 Windows 上使用批处理脚本来实现相同的目标。我编写了以下脚本,该脚本提供了主机名和 IP 地址。但我不知道如何获取网络接口名称。
for /f "skip=1 delims=" %%A in (
'wmic computersystem get name'
) do for /f "delims=" %%B in ("%%A") do set "compName=%%A"
echo hostname is %compName%
此脚本提供主机名/计算机名。
请帮我获取网络接口名称。
非常感谢。 问候, 好想
【问题讨论】:
-
试试,
for /f "tokens=2-5 delims=," %%a in ('wmic nic where "netconnectionid like '%%'" get MACAddress^,AdapterType^,NetConnectionId^,Name /format:csv') do ( echo %%a, %%b, %%c, %%d ) -
您好 elzooilogico,我尝试了您的建议。你能指出任何你看到的错误吗: for /f "tokens=2-5 delims=," %%a in ('wmic nic where "netconnectionid like '%%'" get MACAddress^,AdapterType^, NetConnectionId^,Name /format:csv') do ( echo %%a, %%b, %%c, %%d ) 我得到的错误:C:\Users\user>testnew.bat C:\Users\user >for /F "tokens=2-5 delims=," %a in ('wmic nic where "netconnectionid like '%'" get MACAddress,AdapterType,NetConnectionId,Name /format:csv') 做 (echo %a, % b, %c, %d ) 没有可用的实例。无效的 XSL 格式(或)文件名。 C:\用户\用户>
-
我指定了格式的完整路径:for /f "tokens=2-5 delims=," %%a in ('wmic nic where "netconnectionid like '%%'" get MACAddress^,AdapterType ^,NetConnectionId^,Name /format:"%WINDIR%\System32\wbem \en-US\csv"') 做 ( echo %%a, %%b, %%c, %%d ) 结果是:C: \Users\user>testtemp.bat C:\Users\user>for /F "tokens=2-5 delims=," %a in ('wmic nic where "netconnectionid like '%'" get MACAddress,AdapterType,NetConnectionId,名称 /format:"C:\Windows\System32\wbem\en-US\csv"') do (echo %a, %b, %c, %d ) 没有可用的实例。 , , , ) ser>(echo , , ,
-
@yeswant,在命令行
for /f "tokens=2-5 delims=," %a in ('wmic nic where "netconnectionid like '%%'" get MACAddress^,AdapterType^,NetConnectionId^,Name /format:csv') do echo %a, %b, %c, %d中试试这个。如果要放入批处理文件,则必须将任何%写为%%,因此echo %a, %b, ...将是echo %%a, %%b, ... -
感谢 Elzoologico:我从命令行尝试过,结果如下。知道什么是没有可用的实例意味着: C:\Users\user>for /f "tokens=2-5 delims=," %a in ('wmic nic where "netconnectionid like '%%'" get MACAddress^,AdapterType ^,NetConnectionId^,Name /format:csv') do echo %a, %b, %c, %d 没有可用的实例。 , , , s\user>echo , , , C:\Users\user>
标签: windows batch-file networking interface