Created
July 3, 2011 12:36
-
-
Save angad/1062201 to your computer and use it in GitHub Desktop.
ping
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#define PING_TIMEOUT 2 | |
struct in_addr ouraddr = { 0 }; | |
unsigned long global_rtt = 0; | |
//nmap | |
/* A relatively fast (or at least short ;) ping function. Doesn't require a | |
seperate checksum function */ | |
int isup(struct in_addr target) { | |
int res, retries = 3; | |
struct sockaddr_in sock; | |
/*type(8bit)=8, code(8)=0 (echo REQUEST), checksum(16)=34190, id(16)=31337 */ | |
#ifdef __LITTLE_ENDIAN_BITFIELD | |
unsigned char ping[64] = { 0x8, 0x0, 0x8e, 0x85, 0x69, 0x7A }; | |
#else | |
unsigned char ping[64] = { 0x8, 0x0, 0x85, 0x8e, 0x7A, 0x69 }; | |
#endif | |
int sd; | |
struct timeval tv; | |
struct timeval start, end; | |
fd_set fd_read; | |
struct { | |
struct iphdr ip; | |
unsigned char type; | |
unsigned char code; | |
unsigned short checksum; | |
unsigned short identifier; | |
char crap[16536]; | |
} response; | |
sd = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP); | |
bzero((char *)&sock,sizeof(struct sockaddr_in)); | |
sock.sin_family=AF_INET; | |
sock.sin_addr = target; | |
gettimeofday(&start, NULL); | |
while(--retries) { | |
if ((res = sendto(sd,(char *) ping,64,0,(struct sockaddr *)&sock, | |
sizeof(struct sockaddr))) != 64) { | |
printf("sendto in isup returned %d! skipping host.\n", res); | |
return 0; | |
} | |
FD_ZERO(&fd_read); | |
FD_SET(sd, &fd_read); | |
tv.tv_sec = 0; | |
tv.tv_usec = 1e6 * (PING_TIMEOUT / 3.0); | |
while(1) { | |
if ((res = select(sd + 1, &fd_read, NULL, NULL, &tv)) != 1) | |
{ | |
printf("%d\n", res); | |
break; | |
} | |
else { | |
read(sd,&response,sizeof(response)); | |
printf("Response %d %d %d %d", response.ip.saddr, response.type, response.code, response.identifier); | |
if (response.ip.saddr == target.s_addr && !response.type | |
&& !response.code && response.identifier == 31337) { | |
gettimeofday(&end, NULL); | |
global_rtt = (end.tv_sec - start.tv_sec) * 1e6 + end.tv_usec - start.tv_usec; | |
ouraddr.s_addr = response.ip.daddr; | |
close(sd); | |
return 1; | |
} | |
} | |
} | |
} | |
close(sd); | |
printf("UNREACHABLE. SOCKET CLOSED \n"); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment