Search code examples
batch-filecommandip-address

Only get IPv4 address without the "IPv4 Address. . . . . . . . . . . :" in bat-file


I will create a little batch file to copy my IP address directly to my clipboard. I have tried:

@echo off
ipconfig | find "IPv4" | clip
pause

But gives me: IPv4 Address. . . . . . . . . . . : 192.168.xx.xx. Is there a way to only get 192.168.xx.xx?


Solution

  • for /f "tokens=2 delims=[]" %%a in ('ping -n 1 -4 ""') do echo %%a | clip
    
    • Execute a ping command to local machine (""), sending only one packet (-n 1) using ipv4 (-4)

    • The output of the ping command is processed inside a for /f command

    • The first line in the ping output includes the ip address enclosed in square brackets

    • The for /f tokenizes the line using the square brackets as delimiters, and retrieve the second token

                             v       v          (delimiters)
        Pinging computername [x.x.x.x] with 32 bytes of data
        1                     2       3             (tokens)