#code=936
ENVI^ EnviMode=1

//常数
ENVI &&INVALID_HANDLE=0xFFFFFFFF  //-1 的ULONG 形式
// 从DLL 导入3函数 
ENVI^ Alias IcmpCreateFile=CALL $--ret:*  IPHLPApi.DLL,IcmpCreateFile,
ENVI^ Alias IcmpSendEcho=CALL $--ret:*  IPHLPApi.DLL,IcmpSendEcho,
ENVI^ Alias IcmpCloseHandle=CALL $--ret:*  IPHLPApi.DLL,IcmpCloseHandle,

//PING 主机 [返回名 [返回数据名]]
// 返回1:成功  0：失败
_SUB PING
	ENVI  %2=0
	ENVI#$ &&SendData = 0x31 0x32 0x33 0x34 0x35 0x36  //发送数据 
	ENVI-addr  &&pSendData;&&lSendData=&SendData
	
	ENVI#$ &&__ReplyBuffer= 
	ENVI &&nmReplyBuffer=&__ReplyBuffer
	FIND $X=X%~3,! ENVI &&nmReplyBuffer=%~3
	ENVI#$ %&nmReplyBuffer%= *1060  _ //0x00    //接收缓存区  
	ENVI-addr  &&pReplyBuffer;&&lReplyBuffer=%&nmReplyBuffer%
	
	SOCK --gethostbyname# &&IP;%~1   //转换成整数IP 
	
	ENVI &&hIcmpFile=
	IcmpCreateFile &hIcmpFile  //打开句柄
	FIND $X%&INVALID_HANDLE% = X%&hIcmpFile%, EXIT  //失败
	IcmpSendEcho &&__ret,#%&hIcmpFile% ,#%&IP%,#%&pSendData% ,#%&lSendData%,#0 ,#%&pReplyBuffer% ,#%&lReplyBuffer% ,#1000 
	ENVI  %2=%&__ret%
    IcmpCloseHandle &&ret3,#%&hIcmpFile%  //关闭句柄
_END


// 回应数据的结构ICMP_ECHO_REPLY ： 
//  IPAddr Address;  ULONG Status;  ULONG RoundTripTime;  USHORT DataSize;  USHORT Reserved;
//  PVOID Data;  IP_OPTION_INFORMATION Options;
//DecodePingReplay PING返回值 PING返回数据名
_SUB DecodePingReplay 
 	IFEX $%~1 < 1,  EXIT  
 	GETF -bin %~2,0#20,&&HEAD
 	MSTR * &&D1,&&D2,&&D3,&&D4=<1*>&HEAD  
 	CALC #&D1=%&D1%
 	CALC #&D2=%&D2%
 	CALC #&D3=%&D3%
 	CALC #&D4=%&D4%
 	ENVI &&IP=%&D1%.%&D2%.%&D3%.%&D4%
 	//MESS 从收到 %&IP% 回应 [%&HEAD%]
 	MSTR * &&D1,&&D2=<13*>&HEAD  
 	CALC #&&DataSize=%&D1% + %&D2% * 0x100 
 	MSTR * &&D1,&&D2,&&D3,&&D4=<17*>&HEAD  
 	CALC -base=16 #&&pData=%&D1% + %&D2% * 0x100 + %&D3% * 0x10000 + %&D4% * 0x1000000
 	ENVI-make &&RData=%&pData%;%&DataSize%
 	ENVI-tow  &&WData=&RData  //转为可显示字符串
 	//GETF -bin &RData,0#*,&&WData //显示0xNN 的数据
 	MESS 从 %&IP% 收到 %&DataSize% 字节 回应 [%&WData%] @ #OK    //
 	//MESS 从 %&IP% 收到 回应 [@%&pData%+%&DataSize%][%&WData%] [%&HEAD%] @ #OK    //
_END


FIND $1 = %&&__MAIN__%,  //END_IMPORT 
FIND $X=X%1, CALL TEST! CALL PING %*
_SUB TEST
	ENVI &&HOST=127.0.0.1
	//ENVI &&HOST=www.sina.com.cn   //127.0.0.1
	ENVI &&RET=-1
	ENVI &&DAT=
	PING %&&HOST% &RET &DAT
	CALL DecodePingReplay %&RET% &DAT
	//MESS  PING %&&HOST% = %&RET%
_END

