-
Notifications
You must be signed in to change notification settings - Fork 0
/
icmp_send.c
61 lines (46 loc) · 1.34 KB
/
icmp_send.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
// Jan Mazur
// 281141
// Function compute_icmp_checksum written by Marcin Bieńkowski.
#include "icmp_send.h"
int icmp_send(int sockfd, int pid, int ttl,
struct in_addr *target_address, int sequence_number){
struct icmphdr icmp_header;
icmp_header.type = ICMP_ECHO;
icmp_header.code = 0;
icmp_header.un.echo.id = pid; //program id
icmp_header.un.echo.sequence = sequence_number; // setting this the same as ttl when calling icmp_send
icmp_header.checksum = 0;
icmp_header.checksum = compute_icmp_checksum (
(u_int16_t*)&icmp_header, sizeof(icmp_header));
struct sockaddr_in recipient;
bzero (&recipient, sizeof(recipient));
recipient.sin_family = AF_INET;
recipient.sin_addr = *target_address;
if( setsockopt(sockfd, IPPROTO_IP, IP_TTL, &ttl, sizeof(int)) < 0){
fprintf(stderr,"setsockopt error: %s\n",strerror(errno));
return -1;
}
ssize_t bytes_sent = sendto (
sockfd,
&icmp_header,
sizeof(icmp_header),
0,
(struct sockaddr*)&recipient,
sizeof(recipient)
);
if( bytes_sent < 0){
printf("błąd przy wysylaniu\n");
return -1;
}
return 0;
}
u_int16_t compute_icmp_checksum (const void *buff, int length)
{
u_int32_t sum;
const u_int16_t* ptr = buff;
assert (length % 2 == 0);
for (sum = 0; length > 0; length -= 2)
sum += *ptr++;
sum = (sum >> 16) + (sum & 0xffff);
return (u_int16_t)(~(sum + (sum >> 16)));
}