2

How do I extract the IPv4 IP Address from the output of ipconfig

I read through this post and it was very helpful. I was just wondering if the is a way I can extract only the IP Addresses (xxx.xxx.xxx.xxx). Best way I could think of using notepad to find all / replace all.

Is there a method that I can use via command line?

2 Answers2

2

How can I extract only a list of IP4 addresses from the output of ipconfig?

Use the following batch file (test.cmd):

@echo off
setlocal
setlocal enabledelayedexpansion
for /f "usebackq tokens=2 delims=:" %%a in (`ipconfig ^| findstr /r "[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*"`) do (
  set _temp=%%a
  rem remove leading space
  set _ipaddress=!_temp:~1!
  echo !_ipaddress!
  )
endlocal

Example usage and output:

> ipconfig | findstr /r "[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*"
   IPv4 Address. . . . . . . . . . . : 192.168.42.78
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . : 192.168.42.129

> test
192.168.42.78
255.255.255.0
192.168.42.129

Further Reading

  • An A-Z Index of the Windows CMD command line - An excellent reference for all things Windows cmd line related.
  • enabledelayedexpansion - Delayed Expansion will cause variables to be expanded at execution time rather than at parse time.
  • for /f - Loop command against the results of another command.
  • ipconfig - Configure IP (Internet Protocol configuration)
  • set - Display, set, or remove CMD environment variables. Changes made with SET will remain only for the duration of the current CMD session.
  • setlocal - Set options to control the visibility of environment variables in a batch file.
  • variables - Extract part of a variable (substring).
DavidPostill
  • 162,382
0

Building on DavidPostill’s answer to the question you linked to,

@echo off
setlocal
setlocal enabledelayedexpansion
rem throw away everything except the IPv4 address line 
for /f "usebackq tokens=*" %%a in (`ipconfig ^| findstr IPv4`) do (
  rem we have for example "IPv4 Address. . . . . . . . . . . : 192.168.42.78"
  rem split on ':' and get 2nd token
  for /f delims^=^:^ tokens^=2 %%b in ('echo %%a') do (
    rem we have " 192.168.42.78"
    rem split on '.' and get 4 tokens (octets)
    for /f "tokens=1-4 delims=." %%c in ("%%b") do (
      set _o1=%%c
      set _o2=%%d
      set _o3=%%e
      set _o4=%%f
      rem strip leading space from first octet
      set _4octet=!_o1:~1!.!_o2!.!_o3!.!_o4!
      echo !_4octet!
      )
    )
  )
endlocal

will list the IPv4 addresses for all the interfaces reported by ipconfig.