52 lines
1.0 KiB
C
52 lines
1.0 KiB
C
//
|
|
// UDP Client Connect
|
|
//
|
|
|
|
#include "netlib.h"
|
|
|
|
int udp_client( const char *host, const char *service )
|
|
{
|
|
int sock; /* tcp socket */
|
|
struct addrinfo hints, *res, *ressave;
|
|
|
|
/* default IPv6 localhost */
|
|
if ( !host || !strlen(host) )
|
|
host = "ip6-localhost";
|
|
|
|
/* get address information */
|
|
bzero(&hints, sizeof(struct addrinfo));
|
|
hints.ai_family = AF_UNSPEC;
|
|
hints.ai_socktype = SOCK_DGRAM;
|
|
if ( getaddrinfo(host, service, &hints, &res) )
|
|
{
|
|
log_error("getaddrinfo");
|
|
return -1;
|
|
}
|
|
ressave = res;
|
|
|
|
while (res)
|
|
{
|
|
sock = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
|
|
if (sock < 0)
|
|
continue; // ignore
|
|
|
|
// connected (allows send()/write() to be used)
|
|
if ( connect(sock, res->ai_addr, res->ai_addrlen) == 0 )
|
|
break; // success
|
|
|
|
// next
|
|
close(sock);
|
|
res = res->ai_next;
|
|
}
|
|
|
|
if ( !res )
|
|
{
|
|
log_error("udp_client");
|
|
return -1;
|
|
}
|
|
|
|
freeaddrinfo(ressave);
|
|
|
|
return sock;
|
|
}
|