Banjo API 1.1.0-alpha
Low-level C99 game development API
Loading...
Searching...
No Matches
net_udp_broadcast_send.c

UDP broadcast sender for LAN discovery.

UDP broadcast sender for LAN discovery.Demonstrates: BJ_NET_HINT_BROADCAST hint, sending to broadcast address. Pair with udp_broadcast_recv.c to test.

#include <banjo/log.h>
#include <banjo/main.h>
#include <banjo/net.h>
#include <banjo/system.h>
#include <banjo/time.h>
#include <stdio.h>
#define PORT 9999
#define BROADCAST_ADDR "255.255.255.255"
int main(int argc, char* argv[]) {
(void)argc;
(void)argv;
return 1;
}
struct bj_error* error = 0;
if (!udp) {
bj_err("broadcast: failed to open socket (%s)", bj_error_message(error));
bj_clear_error(&error);
bj_end();
return 1;
}
bj_info("broadcast: sending announcements on port %d", PORT);
int count = 0;
while (1) {
char message[128];
int len = snprintf(message, sizeof(message), "BANJO_SERVICE:ping:%d", count++);
int sent = bj_send_udp(udp, BROADCAST_ADDR, PORT, message, len, &error);
if (sent < 0) {
bj_err("broadcast: send failed (%s)", bj_error_message(error));
bj_clear_error(&error);
} else {
bj_info("broadcast: sent \"%s\"", message);
}
bj_sleep_ms(2000);
}
bj_end();
return 0;
}
struct bj_error bj_error
Definition api.h:348
struct bj_udp bj_udp
Definition api.h:379
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
void bj_destroy_udp(struct bj_udp *udp)
Closes a UDP socket.
struct bj_udp * bj_create_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_send_udp(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.
@ BJ_NET_HINT_BROADCAST
Enable UDP broadcast (SO_BROADCAST).
Definition net.h:126
@ BJ_NET_HINT_IPV4
Restrict address resolution to IPv4.
Definition net.h:121
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_ms(int milliseconds)
Suspend the current thread for at least the given number of milliseconds.
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.
int main(void)
Header file for time manipulation utilities.