程序代码:
CLEAR
DECLARE LONG WSAStartup IN Ws2_32 LONG, STRING@
DECLARE LONG WSACleanup IN Ws2_32
DECLARE LONG socket IN Ws2_32 LONG, LONG, LONG
DECLARE LONG closesocket IN Ws2_32 LONG
DECLARE LONG inet_addr IN Ws2_32 STRING@
DECLARE LONG inet_ntoa IN Ws2_32 LONG
DECLARE LONG setsockopt IN Ws2_32 LONG, LONG, LONG, LONG@, LONG
DECLARE LONG sendto IN Ws2_32 LONG, STRING@, LONG, LONG, STRING@, LONG
DECLARE LONG recvfrom IN Ws2_32 LONG, STRING@, LONG, LONG, STRING@, LONG@
DECLARE LONG WSAGetLastError IN Ws2_32
DECLARE LONG GetCurrentProcessId IN Kernel32
DECLARE LONG GetTickCount IN Kernel32
DECLARE LONG Sleep IN Kernel32 LONG
_Ping("180.97.33.107")
*_Ping("127.0.0.1")
CLEAR DLLS
RETURN
FUNCTION _Ping(cDestIP)
LOCAL WsaData, IcmpHdr, SockAddr_Dest, SockAddr_From
LOCAL i, hSocket, nTimeout, cRecvBuf, cIP, nVal, nTime
WsaData = REPLICATE(0h00, 398)
WSAStartup(0x202, @WsaData)
hSocket = socket(2, 3, 1)
IF hSocket != -1
nTimeout = 1000
setsockopt(hSocket, 0xFFFF, 0x1006, @nTimeout, 4)
cRecvBuf = REPLICATE(0h00, 1024)
SockAddr_From = REPLICATE(0h00, 16)
SockAddr_Dest = 0h02000000 + BINTOC(inet_addr(@cDestIP), "4RS") + 0h0000000000000000
FOR i = 1 TO 4
IcmpHdr = 0h08000000; && 请求应答
+ LEFT(BINTOC(GetCurrentProcessId(), "4RS"), 2);
+ BINTOC(i-1, "2RS");
+ BINTOC(GetTickCount(), "4RS")
IcmpHdr = STUFF(IcmpHdr, 3, 2, LEFT(BINTOC(_CheckSum(IcmpHdr, LEN(IcmpHdr)), "4RS"), 2))
IF sendto(hSocket, @IcmpHdr, LEN(IcmpHdr), 0, @SockAddr_Dest, LEN(SockAddr_Dest)) != -1
nVal = LEN(SockAddr_From)
nVal = recvfrom(hSocket, @cRecvBuf, LEN(cRecvBuf), 0, @SockAddr_From, @nVal)
nTime = GetTickCount()
IF nVal != -1
IF nVal >= (20 + LEN(IcmpHdr))
cIP = SYS(2600, inet_ntoa(CTOBIN(SUBSTR(cRecvBuf, 13, 4), "4RS")), 16)
cIP = LEFT(cIP, AT(0h00, cIP) - 1)
IF (ASC(SUBSTR(cRecvBuf, 10, 1)) == 1) AND ; && 是ICMP协议
(cIP == cDestIP) AND ;
(ASC(SUBSTR(cRecvBuf, 21, 1)) == 0) AND ; && 响应应答
(CTOBIN(SUBSTR(cRecvBuf, 25, 2), "2RS") == GetCurrentProcessId())
nTime = nTime - CTOBIN(SUBSTR(cRecvBuf, 29, 4), "4RS")
* 来自 180.97.33.107 的回复: 字节=32 时间=46ms TTL=53
? "来自 " + cIP
?? " 的回复: 字节=" + TRANSFORM(nVal)
?? " 时间" + IIF(nTime < 1, "<1", "=" + TRANSFORM(nTime)) + "ms"
?? " TTL=" + TRANSFORM(ASC(SUBSTR(cRecvBuf, 9, 1))) && IP头ip_ttl
Sleep(1000)
ENDIF
ENDIF
ELSE
nVal = WSAGetLastError()
IF nVal == 10060
? "请求超时"
ELSE
? "Error: " + TRANSFORM(nVal)
ENDIF
ENDIF
ENDIF
ENDFOR
ELSE
nVal = WSAGetLastError()
IF nVal == 10013
? "因权限被拒,可尝试以管理员身份运行主程序。"
ELSE
? "Error: " + TRANSFORM(nVal)
ENDIF
ENDIF
closesocket(hSocket)
WSACleanup()
ENDFUNC
* 校验和
FUNCTION _CheckSum(cBuffer, nSize)
LOCAL i, nCheckSum
i = 1
nCheckSum = 0
DO WHILE nSize > 1
nCheckSum = nCheckSum + CTOBIN(SUBSTR(cBuffer, i, 2) + 0h0000, "4RS")
i = i + 2
nSIze = nSIze - 2
ENDDO
IF nSize == 1
nCheckSum = nCheckSum + ASC(SUBSTR(cBuffer, i, 1))
ENDIF
nCheckSum = BITRSHIFT(nCheckSum, 16) + BITAND(nCheckSum, 0x0000FFFF)
nCheckSum = nCheckSum + BITRSHIFT(nCheckSum, 16)
RETURN BITAND(BITNOT(nCheckSum), 0x0000FFFF)
ENDFUNC