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>
- // ma transform
- 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()
- {
- // creating a raw socket
- int sockfd = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
- if (sockfd < 0) {
- perror("Failed to create socket");
- exit(EXIT_FAILURE);
- }
- char ip[16];
- scanf("%s", ip);
- struct sockaddr_in dest_addr = {0};
- dest_addr.sin_family = AF_INET;
- if (inet_pton(AF_INET, ip, &(dest_addr.sin_addr)) <= 0) {
- perror("Invalid IP");
- exit(EXIT_FAILURE);
- }
- for(int ttl = 1;;ttl++)
- {
- // Set the ttl on the socket
- setsockopt(sockfd, IPPROTO_IP, IP_TTL, &ttl, sizeof(ttl));
- /// Create the ICMP echo request
- struct icmphdr icmp_packet = {0};
- icmp_packet.checksum = 0;
- icmp_packet.type = ICMP_ECHO;
- icmp_packet.code = 0;
- icmp_packet.un.echo.id = htons(getpid());
- icmp_packet.un.echo.sequence = htons(ttl);
- icmp_packet.checksum = checksum(&icmp_packet, sizeof(icmp_packet));
- /// send the packet
- sendto(sockfd, &icmp_packet, sizeof(icmp_packet), 0, (struct sockaddr*)&dest_addr, sizeof(dest_addr));
- /// receiving the response
- char packet[1500];
- struct sockaddr_in sourceAddress;
- socklen_t sourceLength = sizeof(sourceAddress);
- ssize_t recv_len = recvfrom(sockfd, packet, sizeof(packet), 0, (struct sockaddr*)&sourceAddress, &sourceLength);
- if (recv_len < 0) {
- // timeout or no response
- continue;
- }
- // ughh??
- struct iphdr *ip_header = (struct iphdr *) packet;
- struct icmphdr *icmp_response = (struct icmphdr *)(packet + ip_header->ihl * 4);
- // this is black magic
- char src_ip[INET_ADDRSTRLEN];
- inet_ntop(AF_INET, &(ip_header->saddr), src_ip, INET_ADDRSTRLEN);
- printf("%s\n", src_ip);
- // stopping if we find the echo reply
- if (icmp_response->type == ICMP_ECHOREPLY) {
- break;
- }
- }
- close(sockfd);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement