0

您将如何检测 IP 冲突?

我正在尝试实现两个系统的故障转移。让我们假设他们使用 IP XXX1 和 XXX2(为方便起见,A 和 B),A 作为主服务器,B 作为备份。

A 和 B 都会不断 ping XXX1。如果 A 出现故障,B 将检测到“请求超时”,并使用以下命令将自身转换为 XXX1:

netsh int ipv4 set address name="Local Area Connection" source=static address=X.X.X.1 mask=255.255.255.0 gateway=none

当 A 重新连接自己时,我希望故障转移能够顺利且自动地发生。现在,既然有两台机器用XXX1,就会有IP冲突。B 保留 XXX1,而 A 作为“后来的”计算机将收到此冲突。当 A 再次尝试 ping XXX1 时,A 反而收到:

PING: General failure.

然后 A 会以某种方式检测到这一点并将自己转换为 XXX2。现在两台机器都运行良好,只是它们是镜像的。

或者这就是逻辑。目前,我无法检测到 PING:一般故障。怎么做呢?

或者,如果有更好的方法来进行故障转移,那会是什么?

4

2 回答 2

1

I think you need to redirect the ping command's stderr to stdout with 2>&1 before you can test for errors.

:loop
ping x.x.x.1 2>&1 | find /i "general failure" && (
        netsh int ipv4 set address name="Local Area Connection" source=static address=X.X.X.2 mask=255.255.255.0 gateway=none
)
goto loop

It might be better to check for success rather than failure. Here's something a little more robust that should switch from .2 to .1 if .1 dies; and from .1 to .2 if conflict.

@echo off
setlocal

:: Host to ping
set primary=x.x.x.1
:: Ping with options (1 ping sent per loop, wait 500 ms for timeout)
set ping_options=-n 1 -w 500
:: Fail over after x ping failed responses
set fail_limit=5

:loop

:: Ping x.x.x.1.  Test for "reply from".  If success, set failures=0; otherwise, increment failures
( ping %ping_options% %primary% 2>&1 | find /i "reply from" >NUL && set failures=0 ) || set /a "failures+=1"

:: If failures >= limit, switch IP
if failures GEQ %fail_limit% call :switch

:: Pause for a second and begin again.
ping -n 2 0.0.0.0 >NUL
goto loop


:: Switch subroutine
:switch

:: Get current IPv4 address
for /f "tokens=2 delims={}," %%I in ('wmic nicconfig where ipenabled="TRUE" get ipaddress /format:list') do set IP=%%~I

:: If the last character if the current IP is 1, switch to 2 (or vice versa)
if %IP:~-1%==1 ( set other=%IP:0,-1%2 ) else set other=%IP:0,-1%1

:: Perform the switch
netsh int ipv4 set address name="Local Area Connection" source=static address=%other% mask=255.255.255.0 gateway=none
于 2013-03-18T14:09:38.463 回答
0

As batch lines, perhaps

ping ..whateveryou'dusetogeneratetheerror.. X.X.X.1 |find /i "General failure" >nul
if not errorlevel 1 netsh...(as above)
于 2013-03-18T14:09:51.050 回答