Created
May 31, 2012 17:54
-
-
Save dmh2000/2845062 to your computer and use it in GitHub Desktop.
simple UDP receiver in C using libuv from node.js platform
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
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
I borrowed the 'CHECK' macro from https://gist.github.com/1195428 by utaal.