Banjo API 1.0.0-rc.2
Low-level C99 game development API
Loading...
Searching...
No Matches
net_udp_broadcast_send.c
Go to the documentation of this file.
1
9
10#include <banjo/log.h>
11#include <banjo/main.h>
12#include <banjo/net.h>
13#include <banjo/system.h>
14#include <banjo/time.h>
15
16#include <stdio.h>
17
18#define PORT 9999
19#define BROADCAST_ADDR "255.255.255.255"
20
21int main(int argc, char* argv[]) {
22 (void)argc;
23 (void)argv;
24
25 if (!bj_begin(BJ_NETWORK_SYSTEM, 0)) {
26 return 1;
27 }
28
29 struct bj_error* error = 0;
30
31 struct bj_udp* udp = bj_open_udp(0, 0, BJ_BROADCAST | BJ_RESOLVE_IPV4, &error);
32 if (!udp) {
33 bj_err("broadcast: failed to open socket (%s)", bj_error_message(error));
34 bj_clear_error(&error);
35 bj_end();
36 return 1;
37 }
38
39 bj_info("broadcast: sending announcements on port %d", PORT);
40
41 int count = 0;
42 while (1) {
43 char message[128];
44 int len = snprintf(message, sizeof(message), "BANJO_SERVICE:ping:%d", count++);
45
46 int sent = bj_udp_send(udp, BROADCAST_ADDR, PORT, message, len, &error);
47 if (sent < 0) {
48 bj_err("broadcast: send failed (%s)", bj_error_message(error));
49 bj_clear_error(&error);
50 } else {
51 bj_info("broadcast: sent \"%s\"", message);
52 }
53
54 bj_sleep(2000);
55 }
56
57 bj_close_udp(udp);
58 bj_end();
59 return 0;
60}
int main(int argc, char *argv[])
Definition audio_pcm.c:177
struct bj_error bj_error
Definition api.h:333
struct bj_udp bj_udp
Definition api.h:358
const char * bj_error_message(const struct bj_error *error)
Gets the error message from an error object.
void bj_clear_error(struct bj_error **error)
Frees an error and sets the pointer to NULL.
#define bj_info(...)
Log a message using the BJ_LOG_INFO level.
Definition log.h:141
#define bj_err(...)
Log a message using the BJ_LOG_ERROR level.
Definition log.h:169
struct bj_udp * bj_open_udp(const char *host, uint16_t port, uint16_t hints, struct bj_error **error)
Opens a UDP socket bound to the specified port.
int bj_udp_send(struct bj_udp *udp, const char *host, uint16_t port, const void *data, size_t len, struct bj_error **error)
Sends a datagram to the specified destination.
void bj_close_udp(struct bj_udp *udp)
Closes a UDP socket.
@ BJ_RESOLVE_IPV4
Restrict address resolution to IPv4.
Definition net.h:118
@ BJ_BROADCAST
Enable UDP broadcast (SO_BROADCAST).
Definition net.h:123
bj_bool bj_begin(int systems, struct bj_error **error)
Initialises the system.
void bj_end(void)
De-initialises the system.
@ BJ_NETWORK_SYSTEM
Definition system.h:82
void bj_sleep(int milliseconds)
Suspends the current thread for a specified duration.
Logging utility functions.
Portable main() replacement with platform-aware entry shim.
Header file for network API.
#define PORT
#define BROADCAST_ADDR
Header file for system interactions.
Header file for time manipulation utilities.