123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354 |
- /*
- * 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) {
- shutdown(sock, SHUT_RDWR);
- close(sock);
- }
|