Procházet zdrojové kódy

add tcpserver files

Helmut Pozimski před 4 roky
rodič
revize
c74118b6ff
2 změnil soubory, kde provedl 64 přidání a 0 odebrání
  1. 53 0
      src/tcpserver.c
  2. 11 0
      src/tcpserver.h

+ 53 - 0
src/tcpserver.c

@@ -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);
+}

+ 11 - 0
src/tcpserver.h

@@ -0,0 +1,11 @@
+/*
+ * SPDX-FileCopyrightText: 2019 Helmut Pozimski <helmut@pozimski.eu>
+ *
+ * SPDX-License-Identifier: GPL-2.0-only
+ */
+
+#include <stdint.h>
+ 
+int tcpserver_start(const char *address, uint16_t port);
+void tcpserver_stop(int sock);
+