ntp_server: move code to udp_server.c

This commit is contained in:
Max Kellermann
2011-08-30 07:39:05 +02:00
parent 195496333b
commit 74a39c715b
7 changed files with 219 additions and 142 deletions

View File

@@ -46,78 +46,6 @@ on_quit(void)
io_thread_quit();
}
static int bind_host(int sd, char *hostname, unsigned long ulAddr,
unsigned short *port)
{
struct sockaddr_in my_addr;
socklen_t nlen = sizeof(struct sockaddr);
struct hostent *h;
memset(&my_addr, 0, sizeof(my_addr));
/* use specified hostname */
if (hostname) {
/* get server IP address (no check if input is IP address or DNS name) */
h = gethostbyname(hostname);
if (h == NULL) {
if (strstr(hostname, "255.255.255.255") == hostname) {
my_addr.sin_addr.s_addr=-1;
} else {
if ((my_addr.sin_addr.s_addr = inet_addr(hostname)) == 0xFFFFFFFF) {
return -1;
}
}
my_addr.sin_family = AF_INET;
} else {
my_addr.sin_family = h->h_addrtype;
memcpy((char *) &my_addr.sin_addr.s_addr,
h->h_addr_list[0], h->h_length);
}
} else {
// if hostname=NULL, use INADDR_ANY
if (ulAddr)
my_addr.sin_addr.s_addr = ulAddr;
else
my_addr.sin_addr.s_addr = htonl(INADDR_ANY);
my_addr.sin_family = AF_INET;
}
/* bind a specified port */
my_addr.sin_port = htons(*port);
if (bind(sd, (struct sockaddr *) &my_addr, sizeof(my_addr)) < 0) {
return -1;
}
if (*port == 0) {
getsockname(sd, (struct sockaddr *) &my_addr, &nlen);
*port = ntohs(my_addr.sin_port);
}
return 0;
}
static int
open_udp_socket(char *hostname, unsigned short *port)
{
int sd;
int size = 30000;
/* socket creation */
sd = socket(PF_INET, SOCK_DGRAM, 0);
if (sd < 0) {
return -1;
}
if (setsockopt(sd, SOL_SOCKET, SO_SNDBUF, (void *) &size, sizeof(size)) < 0) {
return -1;
}
if (bind_host(sd, hostname, 0, port)) {
close(sd);
return -1;
}
return sd;
}
int
main(G_GNUC_UNUSED int argc, G_GNUC_UNUSED char **argv)
{
@@ -128,15 +56,14 @@ main(G_GNUC_UNUSED int argc, G_GNUC_UNUSED char **argv)
struct ntp_server ntp;
ntp_server_init(&ntp);
int fd = open_udp_socket(NULL, &ntp.port);
if (fd < 0) {
g_printerr("Failed to create UDP socket\n");
ntp_server_close(&ntp);
GError *error = NULL;
if (!ntp_server_open(&ntp, &error)) {
io_thread_deinit();
g_printerr("%s\n", error->message);
g_error_free(error);
return EXIT_FAILURE;
}
ntp_server_open(&ntp, fd);
io_thread_run();
ntp_server_close(&ntp);