我如何获得的IP地址到一个批处理文件变量? [英] How do I get the IP address into a batch-file variable?

查看:358
本文介绍了我如何获得的IP地址到一个批处理文件变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个奇怪的问题,如果有可能不知道。

I have an odd question, not sure if its possible.

我想编写一个脚本,比​​如我要使用IPCONFIG作为我的命令。

I'd like to write a script, and for example I'm going to use ipconfig as my command.

现在,当您正常运行此命令那里有一吨的输出。

Now when you normally run this command theres a ton of output.

我想有一个脚本,将只显示IP地址,例如

What I'd like to have is a script that would show only the IP address, for example.

echo Network Connection Test
ipconfig <---This would run in the background
echo Your IP Address is: (INSERT IP ADDRESS HERE)

将输出

Network Connection Test

Your IP Address is: 192.168.1.1

这甚至可能吗?

推荐答案

这将打印的IP地址中的输出 IPCONFIG

This will print the IP addresses in the output of ipconfig:

@echo off
set ip_address_string="IP Address"
rem Uncomment the following line when using Windows 7 (with removing "rem")!
rem set ip_address_string="IPv4 Address"
echo Network Connection Test
for /f "usebackq tokens=2 delims=:" %%f in (`ipconfig ^| findstr /c:%ip_address_string%`) do echo Your IP Address is: %%f

要只打印第一个IP地址,只需添加转到:EOF (或其他标签跳转到代替的:EOF ),或在一个更可读的形式:

To only print the first IP address, just add goto :eof (or another label to jump to instead of :eof) after the echo, or in a more readable form:

set ip_address_string="IP Address"
rem Uncomment the following line when using Windows 7 or Windows 8 / 8.1 (with removing "rem")!
rem set ip_address_string="IPv4 Address"
for /f "usebackq tokens=2 delims=:" %%f in (`ipconfig ^| findstr /c:%ip_address_string%`) do (
    echo Your IP Address is: %%f
    goto :eof
)

一个更可配置的方式是真正分析的输出IPCONFIG / ALL 一点点,这样,你甚至可以指定希望其IP地址的适配器:

A more configurable way would be to actually parse the output of ipconfig /all a little bit, that way you can even specify the adapter whose IP address you want:

@echo off
setlocal enabledelayedexpansion
::just a sample adapter here:
set "adapter=Ethernet adapter VirtualBox Host-Only Network"
set adapterfound=false
echo Network Connection Test
for /f "usebackq tokens=1-2 delims=:" %%f in (`ipconfig /all`) do (
    set "item=%%f"
    if /i "!item!"=="!adapter!" (
        set adapterfound=true
    ) else if not "!item!"=="!item:IP Address=!" if "!adapterfound!"=="true" (
        echo Your IP Address is: %%g
        set adapterfound=false
    )
)

这篇关于我如何获得的IP地址到一个批处理文件变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆