Skip to content

Instantly share code, notes, and snippets.

@dmh2000
Created May 31, 2012 17:54
Show Gist options
  • Save dmh2000/2845062 to your computer and use it in GitHub Desktop.
Save dmh2000/2845062 to your computer and use it in GitHub Desktop.
simple UDP receiver in C using libuv from node.js platform
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "uv.h"
// uv1.c
// compile with : gcc -o uv1 -I libuv/include -Wall uv1.c libuv/uv.a -lpthread -lm -lrt
#define CHECK(r, msg) \
if (r) { \
uv_err_t err = uv_last_error(uv_loop); \
fprintf(stderr, "%s: %s\n", msg, uv_strerror(err)); \
exit(1); \
}
static uv_loop_t *uv_loop;
static uv_udp_t server;
void on_recv(uv_udp_t* handle, ssize_t nread, uv_buf_t buf,struct sockaddr* addr, unsigned flags)
{
if (nread > 0) {
printf("%lu\n",nread);
printf("%s",buf.base);
}
printf("free :%lu %p\n",buf.len,buf.base);
free(buf.base);
}
uv_buf_t on_alloc(uv_handle_t* client, size_t suggested_size)
{
uv_buf_t buf;
buf.base = malloc(suggested_size);
buf.len = suggested_size;
printf("malloc:%lu %p\n",buf.len,buf.base);
return buf;
}
int main(int argc,char *argv[])
{
int status;
struct sockaddr_in addr;
uv_loop = uv_default_loop();
status = uv_udp_init(uv_loop,&server);
CHECK(status,"init");
addr = uv_ip4_addr("0.0.0.0", 11000);
status = uv_udp_bind(&server,addr,0);
CHECK(status,"bind");
status = uv_udp_recv_start(&server, on_alloc,on_recv);
CHECK(status,"recv");
uv_run(uv_loop);
return 0;
}
@dmh2000
Copy link
Author

dmh2000 commented May 31, 2012

I borrowed the 'CHECK' macro from https://gist.github.com/1195428 by utaal.

@dam2k
Copy link

dam2k commented Sep 7, 2018

Please use calloc(1, suggested_size) instead of malloc(suggested_size) or you'll risk security and stability issue due to unterminated string

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment