|
@@ -0,0 +1,53 @@
|
|
|
+/*
|
|
|
+ * SPDX-FileCopyrightText: 2019 Helmut Pozimski <helmut@pozimski.eu>
|
|
|
+ *
|
|
|
+ * SPDX-License-Identifier: GPL-2.0-only
|
|
|
+ */
|
|
|
+
|
|
|
+#include <unistd.h>
|
|
|
+#include <sys/socket.h>
|
|
|
+#include <netinet/in.h>
|
|
|
+#include <arpa/inet.h>
|
|
|
+
|
|
|
+/*
|
|
|
+ * Function: tcpserver_start
|
|
|
+ * ----------------------------
|
|
|
+ * Creates a socket and starts to listen on a specified port and address
|
|
|
+ *
|
|
|
+ * address: the IPv4 address to listen to
|
|
|
+ * port: the TCP port to bind to
|
|
|
+ *
|
|
|
+ * returns: the socket used for the connection, -1 on failures
|
|
|
+ */
|
|
|
+int tcpserver_start(const char *address, uint16_t port) {
|
|
|
+ struct sockaddr_in server;
|
|
|
+ int sock;
|
|
|
+ server.sin_family = AF_INET;
|
|
|
+ server.sin_port = htons(port);
|
|
|
+ inet_pton(AF_INET ,address, &server.sin_addr.s_addr);
|
|
|
+ if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
|
|
|
+ close(sock);
|
|
|
+ return -1;
|
|
|
+ }
|
|
|
+ if (bind(sock, (struct sockaddr*) &server, sizeof(server)) < 0 ) {
|
|
|
+ close(sock);
|
|
|
+ return -1;
|
|
|
+ }
|
|
|
+ if (listen(sock, 1) != 0) {
|
|
|
+ close(sock);
|
|
|
+ return -1;
|
|
|
+ }
|
|
|
+ return sock;
|
|
|
+}
|
|
|
+
|
|
|
+/*
|
|
|
+ * Function: tcpserver_stop
|
|
|
+ * ------------------------
|
|
|
+ * Stops the tcp server by closing the socket
|
|
|
+ *
|
|
|
+ * sock: the socket used for the connection
|
|
|
+ *
|
|
|
+ */
|
|
|
+void tcpserver_stop(int sock) {
|
|
|
+ close(sock);
|
|
|
+}
|