Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <errno.h>
- #include <unistd.h>
- #include <netdb.h>
- #include <sys/socket.h>
- #include <netinet/in.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <netinet/ip_icmp.h>
- #include <arpa/inet.h>
- #include <string.h>
- char msg[300];
- int main()
- {
- char adr[] = "127.0.0.1";
- int fd=socket(PF_INET,SOCK_DGRAM,IPPROTO_ICMP);
- if (fd==-1) {
- return -1;
- }
- const size_t req_size=8;
- struct icmphdr req;
- req.type=8;
- req.code=0;
- req.checksum=0;
- req.un.echo.id=htons(12);
- req.un.echo.sequence=htons(1);
- struct sockaddr_in sin;
- sin.sin_family = AF_INET;
- sin.sin_addr.s_addr = inet_addr (adr);
- if (sendto(fd,&req,req_size,0,
- (struct sockaddr *) &sin,sizeof(sin))==-1) {
- return -1;
- }
- int n = recv(fd, msg, sizeof(msg), 0);
- if(n <= 0) {
- printf("recv fail\n");
- return -1;
- }
- struct icmphdr rcv_hdr;
- memcpy(&rcv_hdr, msg, sizeof rcv_hdr);
- if (rcv_hdr.type == ICMP_ECHOREPLY) {
- printf("ICMP Reply, id=0x%x, sequence = 0x%x\n",
- rcv_hdr.un.echo.id, rcv_hdr.un.echo.sequence);
- } else {
- printf("Got ICMP packet with type 0x%x ?!?\n", rcv_hdr.type);
- }
- return 0;
- }
- Program output:
- $ ./test
- ICMP Reply, id=0x400, sequence = 0x100
- Tcpdump output:
- $ sudo tcpdump -i lo -X -v icmp
- tcpdump: listening on lo, link-type EN10MB (Ethernet), capture size 65535 bytes
- 15:13:55.398941 IP (tos 0x0, ttl 64, id 37644, offset 0, flags [DF], proto ICMP (1), length 28)
- localhost > localhost: ICMP echo request, id 4, seq 1, length 8
- 0x0000: 4500 001c 930c 4000 4001 a9d2 7f00 0001 E.....@.@.......
- 0x0010: 7f00 0001 0800 f7fa 0004 0001 ............
- 15:13:55.398958 IP (tos 0x0, ttl 64, id 37645, offset 0, flags [none], proto ICMP (1), length 28)
- localhost > localhost: ICMP echo reply, id 4, seq 1, length 8
- 0x0000: 4500 001c 930d 0000 4001 e9d1 7f00 0001 E.......@.......
- 0x0010: 7f00 0001 0000 fffa 0004 0001 ............
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement