endpoint: server: Add server creation logic
Signed-off-by: Ian Moffett <ian@mirocom.org>
This commit is contained in:
@@ -0,0 +1,70 @@
|
||||
/*
|
||||
* Copyright (c) 2026, Chloe Moffett
|
||||
* Provided under the BSD-3 clause
|
||||
*/
|
||||
|
||||
#include <sys/socket.h>
|
||||
#include <netinet/in.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <strings.h>
|
||||
#include <errno.h>
|
||||
#include <unistd.h>
|
||||
#include "endpoint/server.h"
|
||||
#include "endpoint/common.h"
|
||||
|
||||
int
|
||||
endpoint_server_init(struct endpoint_server *svp)
|
||||
{
|
||||
struct sockaddr_in saddr;
|
||||
int error;
|
||||
|
||||
if (svp == NULL) {
|
||||
errno = EINVAL;
|
||||
return -1;
|
||||
}
|
||||
|
||||
svp->sockfd = socket(AF_INET, SOCK_STREAM, 0);
|
||||
if (svp->sockfd < 0) {
|
||||
perror("socket");
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* Assign the address */
|
||||
bzero(&saddr, sizeof(saddr));
|
||||
saddr.sin_family = AF_INET;
|
||||
saddr.sin_port = htons(SERVER_PORT);
|
||||
saddr.sin_addr.s_addr = INADDR_ANY;
|
||||
|
||||
/* Try to bind it */
|
||||
error = bind(svp->sockfd, (struct sockaddr *)&saddr, sizeof(saddr));
|
||||
if (error < 0) {
|
||||
perror("bind");
|
||||
close(svp->sockfd);
|
||||
svp->sockfd = -1;
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* Now mark it is active and listening */
|
||||
error = listen(svp->sockfd, SERVER_BACKLOG);
|
||||
if (error < 0) {
|
||||
perror("listen");
|
||||
close(svp->sockfd);
|
||||
svp->sockfd = -1;
|
||||
return -1;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
int
|
||||
endpoint_server_close(struct endpoint_server *svp)
|
||||
{
|
||||
if (svp == NULL) {
|
||||
errno = EINVAL;
|
||||
return -1;
|
||||
}
|
||||
|
||||
close(svp->sockfd);
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user