[batch-file] How do I get the IP address into a batch-file variable?

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

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.

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)

The output would be

Network Connection Test

Your IP Address is: 192.168.1.1

Is this even possible?

This question is related to batch-file ip

The answer is


Assuming a windows OS as you mention i p config

If you're willing to install some Unixy utilities like a windows-port of grep and cut you can do that. However, in cases like your example with ipconfig it will be a mess in machines with multiple NICs or e.g VMWare.

Powershell might be the tool you want, look here for a example.


tldr;

I wasn't able use any of the above answers in my use case so I used the following command to get the ip address of my Ethernet network adapter and echo it as mentioned in the above question.

In a command line:

for /f "tokens=3 delims=: " %i  in ('netsh interface ip show config name^="Ethernet" ^| findstr "IP Address"') do echo Your IP Address is: %i

Or in a batch file:

for /f "tokens=3 delims=: " %%i  in ('netsh interface ip show config name^="Wi-Fi" ^| findstr "IP Address" ^| findstr [0-9]') do set IP=%%i

For those who are curious to know what all that means, read on

Most commands using ipconfig for example just print out all your IP addresses and I needed a specific one which in my case was for my Ethernet network adapter.

You can see your list of network adapters by using the netsh interface ipv4 show interfaces command. Most people need Wi-Fi or Ethernet.

You'll see a table like so in the output to the command prompt:

Idx     Met         MTU          State                Name
---  ----------  ----------  ------------  ---------------------------
  1          75  4294967295  connected     Loopback Pseudo-Interface 1
 15          25        1500  connected     Ethernet
 17        5000        1500  connected     vEthernet (Default Switch)
 32          15        1500  connected     vEthernet (DockerNAT)

In the name column you should find the network adapter you want (i.e. Ethernet, Wi-Fi etc.).

As mentioned, I was interested in Ethernet in my case.

To get the IP for that adapter we can use the netsh command:

netsh interface ip show config name="Ethernet"

This gives us this output:

Configuration for interface "Ethernet"
    DHCP enabled:                         Yes
    IP Address:                           169.252.27.59
    Subnet Prefix:                        169.252.0.0/16 (mask 255.255.0.0)
    InterfaceMetric:                      25
    DNS servers configured through DHCP:  None
    Register with which suffix:           Primary only
    WINS servers configured through DHCP: None

(I faked the actual IP number above for security reasons )

I can further specify which line I want using the findstr command in the ms-dos command prompt. Here I want the line containing the string IP Address.

netsh interface ip show config name="Ethernet" | findstr "IP Address"

This gives the following output:

 IP Address:                           169.252.27.59

I can then use the for command that allows me to parse files (or multiline strings in this case) and split out the strings' contents based on a delimiter and the item number that I'm interested in.

Note that I am looking for the third item (tokens=3) and that I am using the space character and : as my delimiters (delims=: ).

for /f "tokens=3 delims=: " %i  in ('netsh interface ip show config name^="Ethernet" ^| findstr "IP Address"') do echo Your IP Address is: %i

Each value or token in the loop is printed off as the variable %i but I'm only interested in the third "token" or item (hence tokens=3). Note that I had to escape the | and = using a ^

At the end of the for command you can specify a command to run with the content that is returned. In this case I am using echo to print it out with some other text but you could also assign the value to an environment variable with do set IP=%i for example or what ever you like.

Pretty neat, huh?

If you have any ideas for improving please leave a comment. I'd love to hear it :) Or you could just edit.


If you want PowerShell or WSL2 bash:

I'm just building off of this answer on superuser,
but I found the following options much clearer way to get my LAN IP address:

  1. Find the name of the interface you want to know about
    For me, it was Configuration for interface "Wi-Fi",
    so for me the name is Wi-Fi.
    (Replace "Wi-Fi" in the command below with your interface name)

  2. PowerShell:

    $myip = netsh interface ip show address "Wi-Fi" `
      | where { $_ -match "IP Address"} `
      | %{ $_ -replace "^.*IP Address:\W*", ""}
    
    echo $myip
    

    Output: 192.168.1.10

  3. Or, my edge case, executing command in WSL2:

    netsh.exe interface ip show address "Wi-Fi" \
       | grep 'IP Address' \
       | sed -r 's/^.*IP Address:\W*//'
    
    # e.g.
    export REACT_NATIVE_PACKAGER_HOSTNAME=$(netsh.exe interface ip show address "Wi-Fi" \
       | grep 'IP Address' \
       | sed -r 's/^.*IP Address:\W*//')
    

try something like this

echo "yours ip addresses are:"
ifconfig | grep "inet addr" | cut -d':' -f2 | cut -d' ' -f1

linux like systems


One line command in Windows to get the IP Address.

for /F "tokens=14" %%i in ('"ipconfig | findstr IPv4"') do SET LOCAL_IP=%%i

After this command echo %LOCAL_IP% will print the ip address. Or you can use %LOCAL_IP% as reference variable in your batch script


In Windows 7:

for /f "tokens=1-2 delims=:" %%a in ('ipconfig^|find "IPv4"') do set ip=%%b
set ip=%ip:~1%
echo %ip%
pause

The following code works on any locale of any platform since Windows XP and it looks for the network IP from a (more or less) random of your network cards. It will never take longer than a few milliseconds.

for /f "delims=[] tokens=2" %%a in ('ping -4 -n 1 %ComputerName% ^| findstr [') do set NetworkIP=%%a
echo Network IP: %NetworkIP%

The following one looks for your public IP instead and works on Windows 7 and newer machines.

for /f %%a in ('powershell Invoke-RestMethod api.ipify.org') do set PublicIP=%%a
echo Public IP: %PublicIP%  

You can find detailed explanations of these commands on my blog.


This is a modification of @mousio's answer. My network connection is not persistent hence the IP address of the next adapter gets displayed if the string "IPv4 Address" is missing from ipconfig. The result of ipconfig has 2 blank spaces between adapters. After an adapter is found and 2 blank lines occurs before the "IPv4 Address" text, it assumes it is missing. Tested on Windows 7 64-bit only.

Processing blank lines from @dbenham's answer in: DOS batch FOR loop with FIND.exe is stripping out blank lines?

@echo off

rem --- complete adapter name to find without the ending ":" ---
set adapter=Wireless LAN adapter Wireless Network Connection

rem --- token under an adapter to extract IP address from ---
set IPAddrToken=IPv4 Address

setlocal enableextensions enabledelayedexpansion
set adapterfound=false
set emptylines=0
set ipaddress=

for /f "usebackq tokens=1-3 delims=:" %%e in (`ipconfig ^| findstr /n "^"`) do (

    set "item=%%f"

    if /i "!item!"=="!adapter!" (
        set adapterfound=true
        set emptylines=0
    ) else if not "!item!"=="" if not "!item!"=="!item:%IPAddrToken%=!" if "!adapterfound!"=="true" (
        @rem "!item:%IPAddrToken%=!" --> item with "IPv4 Address" removed
        set ipaddress=%%g
        goto :result
    )
    if "%%f-%%g-!adapterfound!-!emptylines!"=="--true-1" (
        @rem 2nd blank line after adapter found
        goto :result
    )
    if "%%f-%%g-!adapterfound!-!emptylines!"=="--true-0" (
        @rem 1st blank line after adapter found
        set emptylines=1
    )
)

endlocal

:result
    echo %adapter%
    echo.
    if not "%ipaddress%"=="" (
        echo    %IPAddrToken% =%ipaddress%
    ) else (
        if "%adapterfound%"=="true" (
            echo    %IPAddrToken% Not Found
        ) else (
            echo    Adapter Not Found
        )
    )
    echo.

pause

Extracting the address all by itself is a bit difficult, but you can get the entire IP Address line easily.

To show all IP addresses on any English-language Windows OS:

ipconfig | findstr /R /C:"IP.* Address"

To show only IPv4 or IPv6 addresses on Windows 7+:

ipconfig | findstr /R /C:"IPv4 Address"

ipconfig | findstr /R /C:"IPv6 Address"

Here's some sample output from an XP machine with 3 network adapters.

        IP Address. . . . . . . . . . . . : 192.168.1.10
        IP Address. . . . . . . . . . . . : 10.6.102.205
        IP Address. . . . . . . . . . . . : 192.168.56.1

@echo off

FOR /F "tokens=4 delims= " %%i in ('route print ^| find " 0.0.0.0"') do set localIp=%%i

echo Your IP Address is: %localIp%

For my system, I had numerous IPv4 Addresses, only one of which was correct. A simple way to sort out and check it is as follows:

for /f "tokens=1,2* delims=:" %%A in ('ipconfig ^| find "IPv4 Address"') do (
    set "tempip=%%~B"
    set "tempip=!tempip: =!"
    ping !tempip! -n 1 -w 50
    if !errorlevel!==0 (
        set localip=!tempip!
        goto foundlocal
    )
)
:foundlocal

Below script will store the ip address to the variable ip_address

@echo off

call :get_ip_address
echo %ip_address%

goto :eof

REM
REM get the ip address
REM
:get_ip_address
FOR /f "tokens=1 delims=:" %%d IN ('ping %computername% -4 -n 1 ^| find /i "reply"') do (FOR /F "tokens=3 delims= " %%g IN ("%%d") DO set ip_address=%%g)

goto :eof

Ideas from this blog post.


I know this is an older post but I ran across this while trying to solve the same problem in vbscript. I haven't tested this with mulitple network adapters but hope that it's helpful nonetheless.

for /f "delims=: tokens=2" %%a in ('ipconfig ^| findstr /R /C:"IPv4 Address"') do (set tempip=%%a)  
set tempip=%tempip: =%  
echo %tempip%

This assumes Win7. For XP, replace IPv4 Address with IP Address.


if you just want the ip address try this:

#Variable to store ip address
ipaddr=$(hostname -I)

echo "$ipaddr"

The following was all done in cygwin on a Windows XP box.

This will get your IP address. Note that there are backquotes around the hostname command, not single quotes.

ping -n 1 `hostname` | grep "Reply from " | cut -f 3 -d " " | cut -f 1 -d ":"

This will get your subnet.

ping -n 1 `hostname` | grep "Reply from " | cut -f 3 -d " " | cut -f "1 2 3" -d "."

The following will list all hosts on your local network (put it into a script called "netmap"). I had taken the subnet line above and put it into an executable called "getsubnet", which I then called from the following script.

MINADDR=0
MAXADDR=255
SUBNET=`getsubnet`

hostcnt=0

echo Pinging all addresses in ${SUBNET}.${MINADDR}-${MAXADDR}

for i in `seq $MINADDR $MAXADDR`; do
addr=${SUBNET}.$i
ping -n 1 -w 0 $addr > /dev/null

if [ $? -ne 1 ]    
then    
echo $addr UP    
hostcnt=$((hostcnt+1))    
fi

done

echo Found $hostcnt hosts on subnet ${SUBNET}.${MINADDR}-${MAXADDR}

This work even if you have a virtual network adapters or VPN connections:

FOR /F "tokens=4 delims= " %%i in ('route print ^| find " 0.0.0.0"') do set localIp=%%i
echo Your IP Address is: %localIp%

In linux environment:

ip="$(ifconfig eth0 | grep "inet addr:" | awk '{print $2}' | cut -d ':' -f 2)"

or

ip="$(ifconfig eth0 | grep "inet addr:" | awk '{print $2}' | cut -d ':' -f 2)" | echo $ip

example in FreeBSD:

ifconfig re0 | grep -v "inet6" | grep -i "inet" | awk '{print $2}'

If you have more than one IP address configured, you will have more than one IP address in stdout.


Using IPCONFIG is good, unless you want the flexibility of getting the IP of a remote host in addition to the local host. To get it from something like www.google.com using PING try:

for /f "tokens=2 delims=[]" %%f in ('ping -4 -n 1 www.google.com ^|find /i "pinging"') do echo IP=%%f

The result for that example is:

IP=173.194.73.106

To get the first IP of your local host, replace "www.google.com" with "%computername%" without the quotes. Note the "-4" in front will always get the IPv4 address instead of a possible IPv6 address. Omit as needed. Note also that this technique cannot get more than one IP address. If that is your goal, you'll need to use NSLOOKUP with some extra code.

Mind you, if you use NSLOOKUP instead of PING, and the host has more than one IP address, then your variable will have a comma at the end, since each address will be separated by a comma.