unit SockPing;
interface
uses Windows,SysUtils,JWAWinSock2;
const
ICMP_ECHO=8;
ICMP_ECHOREPLY=0;
type
TIcmpHeader=Record
i_type: Byte;
// ICMP packet type
i_code: Byte;
// type subcode
i_chksum: USHORT;
// packet checksum
i_id: USHORT;
// unique packet ID
i_seq: USHORT;
// packet sequence number
timestamp: ULONG;
// timestamp
data:
array[0..31]
of char;
end;
function Ping(
Const Server:
String):boolean;
implementation
function Ping(
Const Server:
String):boolean;
var
Sock:TSocket;
Addr:TSockAddrIn;
WD:WSAData;
ICMPhdr:TIcmpHeader;
datasize,fromlen,Timeout:Integer;
begin
WSAStartup(MakeWord(2,2),WD);
Sock:=WSASocket(AF_INET,SOCK_RAW,IPPROTO_ICMP,
nil,0,WSA_FLAG_OVERLAPPED);
Result:=not(Sock=Invalid_Socket);
if not Result
then exit;
TimeOut:=100;
Result:=not(setsockopt(sock,SOL_SOCKET,SO_RCVTIMEO,@Timeout,Sizeof(Timeout))=SOCKET_ERROR);
if not Result
then exit;
TimeOut:=100;
Result:=not(setsockopt(sock,SOL_SOCKET,SO_SNDTIMEO,@Timeout,Sizeof(Timeout))=SOCKET_ERROR);
if not Result
then exit;
with Addr
do begin
sin_addr.S_addr:=inet_addr(Pchar(Server));
sin_family:=AF_INET;
end;
with ICMPhdr
do begin
i_type:=ICMP_ECHO;
i_code:=0;
i_id:=Ushort(GetCurrentProcessId);
i_chksum:=0;
i_seq:=0;
timestamp:=GetTickCount;
FillChar(data[0],32,0);
end;
DataSize:=Sizeof(icmphdr);
Result:=not(sendto(Sock,ICMPhdr,DataSize,0,@Addr,Sizeof(TSockAddrIn))=SOCKET_ERROR);
if not Result
then exit;
Result:=not(recvfrom(Sock,ICMPhdr,DataSize,0,@Addr,fromlen)=SOCKET_ERROR);
if not Result
then begin
Writeln('
Error! RecvReason: '+SysErrorMessage(WSAGetLastError));
exit;
end;
closesocket(Sock);
WSACleanup;
end;
end.