File: udp_send.c

package info (click to toggle)
nsntrace 4-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, trixie
  • size: 196 kB
  • sloc: ansic: 875; xml: 103; sh: 69; makefile: 38
file content (45 lines) | stat: -rw-r--r-- 929 bytes parent folder | download | duplicates (2)
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
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <netdb.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

int main(int argc, char **argv)
{
	struct sockaddr_in addr = { 0 };
	int port, num, s;

	if (argc != 3) {
		fprintf(stderr, "usage: udp_send port num_packets\n");
		exit(EXIT_FAILURE);
	}
	port = atoi(argv[1]);
	num = atoi(argv[2]);

	if ((s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) {
		fprintf(stderr, "failed to create socket\n");
		exit(EXIT_FAILURE);
	}

	addr.sin_family = AF_INET;
	addr.sin_port = htons(port);
	inet_aton("127.0.0.1", &addr.sin_addr);

	while(num--) {
		char *message = "if not now, when?";
		int ret;

		ret = sendto(s, message, strlen(message), 0,
			     (struct sockaddr *) &addr, sizeof(addr));
		if (ret < 0) {
			fprintf(stderr, "failed to send message\n");
			exit(EXIT_FAILURE);
		}
	}

	return 0;
}