-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathudp_publisher.c
110 lines (90 loc) · 2.48 KB
/
udp_publisher.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
/**
* Publisher of udp packets to test main.c
* This code allows sending "Hello World !" messages to a connected IP/port.
*
* Usage: ./udp_publisher <ip> <port> <nb_message_to_send>
*
* Example for sending 10 message: ./udp_publisher 10.0.2.15 10001 10
* Example for sending infinite messages: ./udp_publisher 10.0.2.15 10001 0
*/
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <string.h>
#include <unistd.h>
#include <stdbool.h>
#define SEND_SK_BUFFER 20971520 // 20MB of socket buffer size
#define UDP_MAX_SIZE 65535
int create_udp_socket(char *address, char *port, uint64_t buffer_size)
{
struct addrinfo *addr_info;
struct addrinfo hints;
memset(&hints, 0, sizeof(hints));
hints.ai_socktype = SOCK_DGRAM;
hints.ai_family = AF_UNSPEC;
hints.ai_flags = AI_PASSIVE | AI_NUMERICSERV;
int rc = getaddrinfo(address, port, &hints, &addr_info);
if (rc != 0)
{
printf("getaddrinfo error: %s\n", gai_strerror(rc));
exit(EXIT_FAILURE);
}
int sockfd = socket(addr_info->ai_family, addr_info->ai_socktype, addr_info->ai_protocol);
if (sockfd < 0)
{
perror("socket()");
exit(EXIT_FAILURE);
}
if (setsockopt(sockfd, SOL_SOCKET, SO_SNDBUF, &buffer_size, sizeof(buffer_size)))
{
perror("Set socket buffer size");
exit(EXIT_FAILURE);
}
// connect socket to destination address
if (connect(sockfd, addr_info->ai_addr, (int)addr_info->ai_addrlen) == -1)
{
perror("Connect failed");
close(sockfd);
exit(EXIT_FAILURE);
}
// free addr_info after usage
freeaddrinfo(addr_info);
return sockfd;
}
int main(int argc, char *argv[])
{
if (argc != 4)
{
printf("Error: arguments not valid\n");
printf("Usage: ./udp_publisher <ip> <port> <nb_messages>\n");
printf("Example: ./udp_publisher 10.0.2.15 10001 10\n");
exit(1);
}
printf("Sending on %s:%s\n", argv[1], argv[2]);
int socket_fd = create_udp_socket(argv[1], argv[2], SEND_SK_BUFFER);
int messages_to_send = atoi(argv[3]);
bool infinite = false;
if (messages_to_send == 0)
infinite = true;
char buf[100];
int buf_len = strlen(buf);
int count = 0;
while (1)
{
if (!infinite)
{
messages_to_send--;
if (messages_to_send < 0)
break;
}
sprintf(buf, "Hello World %d!", count);
buf_len = strlen(buf);
count++;
if (send(socket_fd, buf, buf_len, 0) < 0)
fprintf(stderr, "Error sending response\n");
sleep(1);
}
return 0;
}