How do I do set a variable in Windows command line to an IP?

北城以北 提交于 2019-12-07 11:48:14

问题


Is there an easy way to grab the IP address from my service provider and put it into a variable via command prompt? Something like the following:

SET hostIP = nslookup \address
ECHO %hostIP%

Or

SET hostIP = ipconfig \address
ECHO %hostIP%

回答1:


for /f "skip=1 tokens=2 delims=: " %f in ('nslookup %COMPUTERNAME% ^| find /i "Address"') do echo %f



回答2:


The answer by Arun is good but I found that using NSLOOKUP generates a rogue comma after the hostname when more than one IP is assigned/associated with a given host.

However, I did find another way that resolves the (first assigned) IP from a given host name and doesn't generate the rogue comma - it uses PING. Very fast, very reliable.

for /f "tokens=2 delims=[]" %f in ('ping -4 -n 1 %COMPUTERNAME% ^| find /i "pinging"') do echo IP=%f

It generates a simple IPv4 address for the hostname into the variable IP. If you then do an ECHO %IP% it will show you the IP like: IP=192.168.1.2

Of course, in batch scripts, you're going to need to replace the single %f with %%f. Note the carat ("^") in front of the pipe ("|") symbol, which is required in batch scripts so they don't interpret the pipe, and instead pipes the results of the ping statement to the find statement.




回答3:


If you could use bash, (as in cygwin) this would easily be done using back-ticks to execute anything you want in your SET hostIP line.

As in

export hostIP = `curl 'http://whatsmyip.net' | grep '<title' | awk '{print $8}' | sed -e 's:<.*::g'`



回答4:


Try a batch like this to set environment variables:

ipconfig > ipconfig.out
setx IPADDR /f ipconfig.out /a 7,13
setx IPADDR /f ipconfig.out /a 7,14
setx IPMASK /f ipconfig.out /a 8,14

Exit the command prompt and open a new one. Use SET and look for IPADDR and IPMASK, which are now persistent. To update the variables, you would have to rerun the batch and exit the command prompt. The different coordinates shown account for differences in the IPCONFIG output for Windows 2003 vs Windows 2008 (should work on XP/7 in the same way). Only a found value is written, so the line that fails does no harm as long as nothing is found. Add the gateway with:

setx IPGATE /f ipconfig.out /a 9,12


来源:https://stackoverflow.com/questions/7575119/how-do-i-do-set-a-variable-in-windows-command-line-to-an-ip

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!