1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
| long ping(char* dest,ULONG timeout,UINT TTL)
{
WSADATA wsaData;
SOCKET sock;
DWORD sockopt;
char * buf;
USHORT ip_len = (USHORT)(sizeof(struct enteteIP) + sizeof(struct icmppingmessage));
SOCKADDR_IN remote;
int remote_len = (int)sizeof(remote);
struct enteteIP ip;
struct icmppingmessage icmp;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
return -1;
sock=socket(PF_INET,SOCK_RAW,IPPROTO_ICMP);
if (sock==INVALID_SOCKET)
return -1;
sockopt = 1;
if (setsockopt(sock, IPPROTO_IP, IP_HDRINCL, (char *)&sockopt, sizeof(sockopt)) == SOCKET_ERROR)
return -1;
sockopt = timeout;
if (setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (char *)&sockopt, sizeof(sockopt)) == SOCKET_ERROR)
return -1;
buf = malloc(ip_len);
ip.version = 4;
ip.hlen = 5;
ip.tos = 0;
ip.tot_len = htons(ip_len);
ip.id = htons(1);
ip.flags = 0;
ip.offset = 0;
ip.ttl = TTL;
ip.protocole = IPPROTO_ICMP;
ip.somme = 0;
HOSTENT* host=gethostbyname(dest);
if(host==0)
return 0;
ip.ip_dest = (long)*(long**)(host->h_addr_list[0]);
icmp.type = ICMP_ECHO_REQ;
icmp.code = 0;
icmp.somme = 0;
icmp.id = GetCurrentProcessId();
icmp.timestamp = GetTickCount();
icmp.somme = checksum(&icmp, sizeof(icmp));
memcpy(buf, &ip, sizeof(ip));
memcpy(buf + sizeof(ip), &icmp, sizeof(icmp));
ZeroMemory(&remote, sizeof(remote));
remote.sin_family = AF_INET;
remote.sin_addr.s_addr = (long)*(long**)(gethostbyname(dest)->h_addr_list[0]);
int v1=0,fixe=0;
for(v1=0;(ip.ip_source=HostIP_long(v1))!=0 && fixe==0;v1++)
{
if((ip.ip_source&0xffffff)==(ip.ip_dest&0xffffff))
{
fixe=1;
v1--;
}
}
if(fixe==0)
v1=0;
int reponse=SOCKET_ERROR;
for(v1=v1;(ip.ip_source=HostIP_long(v1))!=0 && reponse==SOCKET_ERROR;v1++)
{
ip.ip_source = HostIP_long(v1);
ip.somme = checksum(&ip, sizeof(ip));
memcpy(buf, &ip, sizeof(ip));
memcpy(buf + sizeof(ip), &icmp, sizeof(icmp));
if (sendto(sock, buf, ip_len, 0, (SOCKADDR *)&remote, remote_len)==SOCKET_ERROR)
return -1;
reponse=recvfrom(sock, buf, ip_len, 0, (SOCKADDR *)&remote, &remote_len);
if(fixe==1 && reponse==SOCKET_ERROR)
{
fixe=0;
v1=-1;
}
}
DWORD delta_t = GetTickCount() - icmp.timestamp;
ZeroMemory(&ip, sizeof(ip));
ZeroMemory(&icmp, sizeof(icmp));
memcpy(&ip, buf, sizeof(ip));
memcpy(&icmp, buf + (ip.hlen * 4), sizeof(icmp));
if (icmp.id != GetCurrentProcessId())
return 0;
else
{
switch(icmp.type)
{
case ICMP_ECHO_REPLY:
return remote.sin_addr.s_addr;
break;
default:
return 0;
break;
}
}
} |
Partager