Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- + (NSString *)makeTrace:(const char *)address :(int)ttl_t :(int)timeout
- {
- struct hostent *host_entry = gethostbyname(address);
- if(host_entry == nil || host_entry->h_addr_list == 0)
- {
- return nil;
- }
- char *ip_addr = inet_ntoa(*((struct in_addr *)host_entry->h_addr_list[0]));
- struct sockaddr_in destination, fromAddr;
- int recv_sock;
- int send_sock;
- if((recv_sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_ICMP)) < 0)
- {
- return nil;
- }
- if((send_sock = socket(AF_INET , SOCK_DGRAM, IPPROTO_IP)) < 0)
- {
- return nil;
- }
- int ttl = (int)ttl_t;
- memset(&destination, 0, sizeof(destination));
- destination.sin_family = AF_INET;
- destination.sin_addr.s_addr = inet_addr(ip_addr);
- destination.sin_port = htons(33434);
- struct timeval tv;
- tv.tv_sec = timeout / 1000;
- tv.tv_usec = (timeout % 1000) * 1000;
- if(setsockopt(recv_sock, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(struct timeval)) < 0)
- {
- return nil;
- }
- NSTimeInterval timeInSeconds = [[NSDate date] timeIntervalSince1970];
- NSString *timestamp = [NSString stringWithFormat:@"%f", timeInSeconds];
- const char *cmsg = [timestamp UTF8String];
- socklen_t n = sizeof(fromAddr);
- int buffer_size = BUFFER_SIZE;
- void *buffer;
- buffer = malloc(buffer_size);
- memset(&fromAddr, 0, sizeof(fromAddr));
- if(setsockopt(send_sock, IPPROTO_IP, IP_TTL, &ttl, sizeof(ttl)) < 0)
- {
- return nil;
- }
- if(sendto(send_sock, cmsg, sizeof(cmsg), 0, (struct sockaddr *) &destination,sizeof(destination)) != sizeof(cmsg))
- {
- return nil;
- }
- ssize_t bytesRead = recvfrom(recv_sock, buffer, buffer_size, 0, (struct sockaddr *)&fromAddr, &n);
- if(setsockopt(recv_sock, SOL_SOCKET, SO_RCVBUF, &buffer_size, sizeof(buffer_size)) < 0)
- {
- return nil;
- }
- NSString *result = nil;
- if(bytesRead > 0)
- {
- char display[INET_ADDRSTRLEN]= {0};
- inet_ntop(AF_INET, &fromAddr.sin_addr.s_addr, display, sizeof (display));
- //@"Received packet from%s for TTL=%d\n";//, display;
- result = [NSString stringWithCString:display encoding:NSUTF8StringEncoding];
- }
- close(send_sock);
- close(recv_sock);
- free(buffer);
- return result;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement