60 lines
1.2 KiB
C
60 lines
1.2 KiB
C
//
|
|
// 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;
|
|
}
|