Arun
Arun

Reputation: 39

CMD command for getting the IPv4 address alone in Windows

"ipconfig" returns all details. but i just want the ipv4.

I have tried "ipconfig | find /I "ipv4" | clip" as well but it returns "IPv4 Address. . . . . . . . . . . : XXX.XXX.X.X"

I donot want "IPv4 Address. . . . . . . . . . . : " as well.

I want the output "xxx.xxx.x.x" nothing else

Is there any cmd command for that for Windows?

Upvotes: 1

Views: 6091

Answers (2)

Joshua Dyck
Joshua Dyck

Reputation: 2173

The accepted answer printed out the wrong IP for my situation. I wanted the IP for a specific network adapter and just the IP so I could pass it into a variable and use it.

I used something similar to the accepted answer to achieve this but with the netsh command and findstr in a for loop:

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

I explain how it works in this related article: https://stackoverflow.com/a/59004409/2684661

I hope this helps some people get what they need.

Upvotes: 0

MC ND
MC ND

Reputation: 70923

You can try

for /f "tokens=2 delims=[]" %a in ('ping -n 1 -4 "%computername%"') do @echo %a

for /f is used to execute some code (the code after the do clause) for each of the lines obtained from: a file on disk or the output of a command or a direct included string.

In this case, the second option is used. A for /f will be used to run a ping command against the computer name and process its output. Inside the output of this ping command there will be a line saying something like Pinging [xxx.xxx.xxx.xxx] with .... . This is the line we want process with the for command. Usually some kind of find command is needed to discard the rest of the lines and keep only the neede one, but in this case it will be not needed.

The delims clause indicates [] will be used as delimiters to split the line. We want the second part of the line, so tokens=2 is used.

As the for /f processes the output of the ping command, each line is parsed. The only line that includes [] is the one we are insterested, so, it is the only line that will be splitted, and the only one that returns a second token (the rest of the lines will only output one token as they are not splitted). This token will be stored in the for replaceable parameter %%a and then echoed to console.

Upvotes: 4

Related Questions