开发者

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

开发者 https://www.devze.com 2023-04-09 01:20 出处:网络
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开发者_高级运维:

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%


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


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.


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'`


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号