1 /*
2  * $smu-mark$
3  * $name: sendudp.c$
4  * $author: Salvatore Sanfilippo <antirez@invece.org>$
5  * $copyright: Copyright (C) 1999 by Salvatore Sanfilippo$
6  * $license: This software is under GPL version 2 of license$
7  * $date: Fri Nov  5 11:55:49 MET 1999$
8  * $rev: 8$
9  */
10 
11 /* $Id: send.c,v 1.1.1.1 2003/08/31 17:23:53 antirez Exp $ */
12 
13 #include <stdio.h>
14 #include <string.h>
15 #include <stdlib.h>
16 #include <sys/time.h>
17 #include <unistd.h>
18 #include <signal.h>
19 #include <errno.h>
20 
21 #include "hping2.h"
22 #include "globals.h"
23 
select_next_random_source(void)24 static void select_next_random_source(void)
25 {
26 	unsigned char ra[4];
27 
28 	ra[0] = hp_rand() & 0xFF;
29 	ra[1] = hp_rand() & 0xFF;
30 	ra[2] = hp_rand() & 0xFF;
31 	ra[3] = hp_rand() & 0xFF;
32 	memcpy(&local.sin_addr.s_addr, ra, 4);
33 
34 	if (opt_debug)
35 		printf("DEBUG: the source address is %u.%u.%u.%u\n",
36 		    ra[0], ra[1], ra[2], ra[3]);
37 }
38 
select_next_random_dest(void)39 static void select_next_random_dest(void)
40 {
41 	unsigned char ra[4];
42 	char a[4], b[4], c[4], d[4];
43 
44 	if (sscanf(targetname, "%4[^.].%4[^.].%4[^.].%4[^.]", a, b, c, d) != 4)
45 	{
46 		fprintf(stderr,
47 			"wrong --rand-dest target host, correct examples:\n"
48 			"  x.x.x.x, 192,168.x.x, 128.x.x.255\n"
49 			"you typed: %s\n", targetname);
50 		exit(1);
51 	}
52 	a[3] = b[3] = c[3] = d[3] = '\0';
53 
54 	ra[0] = a[0] == 'x' ? (hp_rand() & 0xFF) : strtoul(a, NULL, 0);
55 	ra[1] = b[0] == 'x' ? (hp_rand() & 0xFF) : strtoul(b, NULL, 0);
56 	ra[2] = c[0] == 'x' ? (hp_rand() & 0xFF) : strtoul(c, NULL, 0);
57 	ra[3] = d[0] == 'x' ? (hp_rand() & 0xFF) : strtoul(d, NULL, 0);
58 	memcpy(&remote.sin_addr.s_addr, ra, 4);
59 
60 	if (opt_debug) {
61 		printf("DEBUG: the dest address is %u.%u.%u.%u\n",
62 				ra[0], ra[1], ra[2], ra[3]);
63 	}
64 }
65 
66 /* The signal handler for SIGALRM will send the packets */
send_packet(int signal_id)67 void send_packet (int signal_id)
68 {
69 	int errno_save = errno;
70 
71 	if (opt_rand_dest)
72 		select_next_random_dest();
73 	if (opt_rand_source)
74 		select_next_random_source();
75 
76 	if (opt_rawipmode)	send_rawip();
77 	else if (opt_icmpmode)	send_icmp();
78 	else if (opt_udpmode)	send_udp();
79 	else			send_tcp();
80 
81 	sent_pkt++;
82 	Signal(SIGALRM, send_packet);
83 
84 	if (count != -1 && count == sent_pkt) { /* count reached? */
85 		Signal(SIGALRM, print_statistics);
86 		alarm(COUNTREACHED_TIMEOUT);
87 	} else if (!opt_listenmode) {
88 		if (opt_waitinusec == FALSE)
89 			alarm(sending_wait);
90 		else
91 			setitimer(ITIMER_REAL, &usec_delay, NULL);
92 	}
93 	errno = errno_save;
94 }
95