62

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?

indiv
  • 17,306
  • 6
  • 61
  • 82
level42
  • 946
  • 2
  • 13
  • 33
  • 2
    You can have multiple IP addresses and most machines even have multiple ones. So which one do you want? – Joey May 05 '11 at 20:50

19 Answers19

67

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.

Fabio Iotti
  • 1,480
  • 1
  • 16
  • 20
  • 4
    It gives me an error: "%%a was unexpected at this time." – FelikZ Oct 13 '14 at 12:29
  • 2
    This is for batch only, you are probably running it in the command line, right? – Fabio Iotti Oct 13 '14 at 13:50
  • yes. In the file it works perfect. Can you explain why? – FelikZ Oct 13 '14 at 15:01
  • 1
    I think it depends on how the `FOR` command works, and how it threats `%%a` variable. I actually can't explain why it's different, but replacing both occurences of `%%a` with `%a` will make it work in command line. This prevents it to work in batch, of course. – Fabio Iotti Oct 13 '14 at 17:28
  • 1
    Thanks, I found this very useful for three reasons: 1) it selects the correct local network interface 2) it is valid for any windows version, regardless of the language 3) it doesn't give blank spaces at the beginning of the IP address. – Alicia Jan 16 '17 at 12:58
  • 2
    This is fine if you don't have a second local interface. For me it selects IP from Ethernet adapter VirtualBox Host-Only Network #2. When you disable it, it's okay. – Xdg Feb 27 '18 at 09:38
  • I assume this will pick the first network interface with some service that is interesting to Windows (like maybe a DNS or DHCP server). Just out of curiosity: do you have some of such services running on your virtual machine? – Fabio Iotti Feb 27 '18 at 16:35
  • 1
    and if you add -w 0 to the ping it will be even faster ;) – john v kumpf Feb 05 '19 at 21:13
  • `ping` defaults to the wrong adapter (VirtualBox Host-only Network IP adapter) and thus gets you the wrong local IP. You can't specify which adapter in ping, and adapter priority reordering doesn't work here. The only way is to disable the VirtualBox adapters (not a solution) or change back to parsing output from `route` like @SergeyA suggests, or from `ipconfig` – Leeroy Jul 15 '20 at 12:45
51

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

@echo off
set ip_address_string="IPv4 Address"
rem Uncomment the following line when using older versions of Windows without IPv6 support (by removing "rem")
rem set ip_address_string="IP 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

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="IPv4 Address"
rem Uncomment the following line when using older versions of Windows without IPv6 support (by removing "rem")
rem set ip_address_string="IP Address"
for /f "usebackq tokens=2 delims=:" %%f in (`ipconfig ^| findstr /c:%ip_address_string%`) do (
    echo Your IP Address is: %%f
    goto :eof
)

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
    )
)
mousio
  • 10,079
  • 4
  • 34
  • 43
  • 2
    I think you need to change "IP address" to "IP Address", or pass `/I` to `findstr` to do a case-insensitive match. – indiv May 05 '11 at 18:07
  • @indiv: correct (I have a different locale and I manually changed the string); answer is updated… – mousio May 05 '11 at 18:18
  • 3
    On my Win7 computer thing string to match is "IPv4 Address". – Vik David May 05 '11 at 18:48
  • @Vik: thanks for mentioning this, I hope it helps other users. Just update the appropriate string in the script :] – mousio May 05 '11 at 19:01
  • 1
    you can use regex with findstr to test for either string: `findstr /R /C:"^ *IP[v4]* Address"` – Sam Hasler Feb 19 '16 at 14:45
  • Feel free to update/enhance, as others already have. Now I rarely ever use cmd anymore, in favor of PowerShell. – mousio Jun 21 '16 at 17:27
26

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
James A Mohler
  • 11,060
  • 15
  • 46
  • 72
OptekProduction
  • 261
  • 3
  • 2
  • 1
    Thanks for `set ip=%ip:~1%` to get rid of the additional space in front. :) – sudheeshix Oct 05 '16 at 07:18
  • 1
    `for /f "tokens=14 delims= " %%a in ('ipconfig^|find "IPv4"') do set ip=%%a` That would be shorter version using "space" instead of a colon ":" as a delimiter to get everything **after the last space** as a result variable **%ip%** How it works? Example result of **ipconfig^ | find "IPv4"** is: `IPv4 Address. . . . . . . . . . . : 127.0.0.1`. There are **13 spaces** thus we set **tokens=14** and assign this token **%a** to variable **ip** without unnecessary space. @sudheeshix @optekproductions – konieckropka May 14 '22 at 03:43
20
@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%
16

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
indiv
  • 17,306
  • 6
  • 61
  • 82
  • 1
    On >= Windows 7, you should find the string "IPv4 Address" (instead of "IP Address"), so the correct command looks like this: `ipconfig | findstr /R /C:"IPv4 Address.*:"`. I think you should add it to your post. :) I upvoted it though, because it's another good idea. :) – Sk8erPeter Nov 21 '13 at 18:01
  • @Sk8erPeter: Thanks! I've updated the answer with new regexes. – indiv Nov 21 '13 at 19:36
  • You're welcome! And thanks for updating it. The `ipconfig | findstr /R /C:"IP.* Address"` which you just wrote is an even better idea :) – Sk8erPeter Nov 22 '13 at 16:50
  • 1
    `ipconfig | findstr /R /C:"IP.*"` this is better if language differ from english – Николай Мишин May 12 '15 at 08:24
  • just IPv4 address on Win7 or XP: `ipconfig | findstr /R /C:"^ *IP[v4]* Address"` – Sam Hasler Feb 19 '16 at 14:26
10

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.

Community
  • 1
  • 1
Joshua Dyck
  • 2,113
  • 20
  • 25
  • 1
    Batch files use a slightly different syntax for variables: `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` Notice the variables use a double percent. – Joshua Dyck Jun 09 '20 at 13:04
9

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%
SergeyA
  • 4,427
  • 1
  • 22
  • 15
  • `route print` seems the more reliable and elegant option for Windows systems. This should be the accepted answer. – Leeroy Jul 15 '20 at 12:50
  • 1
    It comes very close to the most ideal solution. It is just that when having multiple (virtual) interfaces using 0.0.0.0, it only stores the last value it finds. Depending on how (and for which specific purpose) one uses the resulting data, it could potentially be another value than someone expect it to be. – script'n'code Sep 24 '20 at 14:44
3

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
Community
  • 1
  • 1
Ian
  • 679
  • 6
  • 10
2

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.

slavoo
  • 5,798
  • 64
  • 37
  • 39
skywalkr73
  • 21
  • 1
2

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.

Lizz
  • 1,442
  • 5
  • 25
  • 51
2

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

vkrams
  • 7,267
  • 17
  • 79
  • 129
1

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.

fvu
  • 32,488
  • 6
  • 61
  • 79
  • This is great thanks, I was looking for a very simple way to perform this, but thanks for the info – level42 May 05 '11 at 14:34
0

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}
0

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.

Mingjiang Shi
  • 7,415
  • 2
  • 26
  • 31
0

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.

Idos
  • 15,053
  • 14
  • 60
  • 75
0

try something like this

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

linux like systems

mivk
  • 13,452
  • 5
  • 76
  • 69
MealstroM
  • 189
  • 1
  • 10
0

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
Mark Deven
  • 550
  • 1
  • 9
  • 21
0

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*//')
    
Daryn
  • 4,791
  • 4
  • 39
  • 52
-3

if you just want the ip address try this:

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

echo "$ipaddr"
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129