Initial commit of files
This commit is contained in:
59
src/libnet/udp_server.c
Normal file
59
src/libnet/udp_server.c
Normal file
@ -0,0 +1,59 @@
|
||||
//
|
||||
// UDP Server
|
||||
//
|
||||
|
||||
#include "netlib.h"
|
||||
|
||||
int udp_server( const char *host, const char *service )
|
||||
{
|
||||
/* socket stuff */
|
||||
int sock; /* tcp socket */
|
||||
|
||||
/* dual stack listener */
|
||||
struct addrinfo hints;
|
||||
struct addrinfo *res, *ressave;
|
||||
|
||||
/* set-up hints structure */
|
||||
bzero(&hints, sizeof(hints));
|
||||
hints.ai_family = AF_UNSPEC;
|
||||
hints.ai_flags = AI_PASSIVE;
|
||||
hints.ai_socktype = SOCK_DGRAM;
|
||||
if ( getaddrinfo(host, service, &hints, &res) )
|
||||
{
|
||||
log_error( "getaddrinfo" );
|
||||
return -1;
|
||||
}
|
||||
ressave = res;
|
||||
|
||||
/*
|
||||
* "res" has a chain of addrinfo structure filled with
|
||||
* 0.0.0.0 (for IPv4), 0:0:0:0:0:0:0:0 (for IPv6) and alike,
|
||||
* with port filled for "myservice".
|
||||
*/
|
||||
while (res)
|
||||
{
|
||||
/* bind() and listen() to res->ai_addr */
|
||||
sock = socket(res->ai_family, res->ai_socktype, res->ai_protocol );
|
||||
if ( sock < 0 )
|
||||
continue;
|
||||
|
||||
/* bind */
|
||||
if ( bind(sock, res->ai_addr, res->ai_addrlen) == 0 )
|
||||
break; // success
|
||||
|
||||
/* error, try again */
|
||||
close( sock );
|
||||
res = res->ai_next;
|
||||
}
|
||||
|
||||
freeaddrinfo( ressave );
|
||||
|
||||
/* able to bind? */
|
||||
if ( !res )
|
||||
{
|
||||
log_error( "server" );
|
||||
return -1;
|
||||
}
|
||||
|
||||
return sock;
|
||||
}
|
||||
Reference in New Issue
Block a user