Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <arpa/inet.h>
- #include <stdio.h>
- #include <string.h>
- #include <stdlib.h>
- #include <sys/socket.h>
- #include <unistd.h>
- #include <stdbool.h>
- #include <netinet/ip_icmp.h>
- unsigned short checksum (void *b, int len) {
- unsigned short * buf = b;
- unsigned int sum = 0;
- unsigned short result;
- for(sum = 0; len > 1; len -= 2)
- sum += * buf ++;
- if(len == 1)
- sum += *(unsigned char *) buf ;
- sum = (sum >> 16) + (sum & 0xFFFF);
- sum += (sum >> 16);
- result = ~sum;
- return result;
- }
- int main()
- {
- char ip[16];
- scanf("%s", ip);
- // creating a raw socket
- int sockfd = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
- if (sockfd < 0) {
- perror("Failed to create socket");
- exit(EXIT_FAILURE);
- }
- // Prepare the ICMP packet
- struct icmphdr icmp_packet = {0};
- memset(&icmp_packet, 0, sizeof(icmp_packet));
- // Structure your packet here (e.g., set type, code, checksum, identifier, sequence number)
- icmp_packet.checksum = 0;
- icmp_packet.type = ICMP_ECHO;
- icmp_packet.code = 0;
- icmp_packet.un.echo.id = getpid();
- icmp_packet.un.echo.sequence = 1;
- icmp_packet.checksum = checksum(&icmp_packet, sizeof(icmp_packet));
- // Fill in the destination address
- struct sockaddr_in dest_addr = {0};
- dest_addr.sin_family = AF_INET;
- // Set dest_addr.sin_addr based on input IP
- if (inet_pton(AF_INET, ip, &(dest_addr.sin_addr)) <= 0) {
- perror("Invalid IP address format");
- exit(EXIT_FAILURE);
- }
- // Send the ICMP packet
- int result = sendto(sockfd, &icmp_packet, sizeof(struct icmphdr), 0, (struct sockaddr*)&dest_addr, sizeof(dest_addr));
- if (result < 0) {
- perror("Failed to send ICMP packet");
- // Handle error
- } else {
- printf("ICMP Echo Request sent successfully.\n");
- }
- char packet[1500]; // A common MTU size is sufficient for buffer
- struct sockaddr_in sourceAddress;
- socklen_t sourceLength = sizeof(sourceAddress);
- // Receive the packet
- ssize_t bytes_received = recvfrom(sockfd, packet, sizeof(packet), 0, (struct
- sockaddr*)&sourceAddress, &sourceLength);
- if (bytes_received < 0) {
- perror("Failed to receive packet");
- // Handle error
- }
- struct iphdr *ip_header = (struct iphdr *)packet;
- struct icmphdr *icmp_header = (struct icmphdr *)(packet + (ip_header->ihl * 4));
- char src_ip[INET_ADDRSTRLEN], dst_ip[INET_ADDRSTRLEN];
- inet_ntop(AF_INET, &(ip_header->saddr), src_ip, INET_ADDRSTRLEN);
- inet_ntop(AF_INET, &(ip_header->daddr), dst_ip, INET_ADDRSTRLEN);
- printf("Destination Address: %s\n", dst_ip);
- printf("Source Address: %s\n", src_ip);
- printf("TTL: %d\n", ip_header->ttl);
- printf("Protocol: %d\n", ip_header->protocol);
- printf("Total Length: %d\n", ntohs(ip_header->tot_len));
- printf("Version: %d\n", ip_header->version);
- close(sockfd);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement