As you have not clarified whether you're looking for a windows batch-file solution, or an ubuntu linux bash shell script, and those 'nix based tags have now been edited out, the following is an example of a Windows batch-file, which should achieve what your provided code attempted to do. Use the ping
command against the computer name to return the IPv4 address, save it as a variable and print the details to the host.
I have written it in such a way as to allow it to function even in Windows 2000, as earlier ping.exe
versions, did not have the -4
option.
@Echo Off
SetLocal EnableExtensions
Set "MY_IP="
For /F "Tokens=2 Delims=[]" %%G In (
'"("%SYSTEMROOT%\System32\ping.exe" "%COMPUTERNAME%" -n 1 -4 2>NUL || "%SYSTEMROOT%\System32\ping.exe" "%COMPUTERNAME%" -n 1 2>NUL) | "%SYSTEMROOT%\System32\find.exe" /I "%COMPUTERNAME%""'
) Do Set "MY_IP=%%G"
If Not Defined MY_IP GoTo :EOF
Echo IP of Current Computer : %MY_IP%
Pause
If you intend using it only on modern versions of Windows OS, then the following shorter version should suffice:
@Echo Off
SetLocal EnableExtensions
Set "MY_IP="
For /F "Tokens=2 Delims=[]" %%G In (
'""%__APPDIR__%ping.exe" "%COMPUTERNAME%" -n 1 -4 2>NUL | "%__APPDIR__%find.exe" /I "%COMPUTERNAME%""'
) Do Set "MY_IP=%%G"
If Not Defined MY_IP GoTo :EOF
Echo IP of Current Computer : %MY_IP%
Pause