WHY2/src/chat/server/main.c

85 lines
2.2 KiB
C
Raw Normal View History

2023-02-09 17:19:49 +01:00
/*
This is part of WHY2
Copyright (C) 2022 Václav Šmejkal
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include <why2/chat/common.h>
2023-02-09 17:53:42 +01:00
void die(char *exit_message);
2023-02-09 18:36:51 +01:00
char *read_socket(int socket);
2023-02-09 09:09:26 +01:00
int main(void)
{
int listen_socket = socket(AF_INET, SOCK_STREAM, 0); //CREATE SERVER SOCKET
2023-02-09 18:25:45 +01:00
int accepted;
char *received = why2_malloc(SEND_LENGTH);
if (listen_socket < 0) die("Failed creating socket.");
//DEFINE SERVER ADDRESS
struct sockaddr_in server_addr;
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(SERVER_PORT);
server_addr.sin_addr.s_addr = INADDR_ANY;
//BIND SOCKET
if (bind(listen_socket, (SA *) &server_addr, sizeof(server_addr)) < 0) die("Failed binding socket.");
//LISTEN
if (listen(listen_socket, 1) < 0) die("Binding failed.");
2023-02-09 09:09:26 +01:00
2023-02-09 18:25:45 +01:00
//LOOP ACCEPT
while (getchar() != '\n') //END WHEN ENTER IS PRESSED
{
accepted = accept(listen_socket, (SA *) NULL, NULL);
}
//DEALLOCATION
why2_deallocate(received);
2023-02-09 09:09:26 +01:00
return 0;
2023-02-09 17:53:42 +01:00
}
void die(char *exit_msg)
{
2023-02-09 18:25:45 +01:00
fprintf(stderr, "%s\n", exit_msg); //ERR MSG
2023-02-09 18:25:45 +01:00
why2_clean_memory(why2_get_default_memory_identifier()); //GARBAGE COLLECTOR
2023-02-09 18:37:15 +01:00
exit(1);
2023-02-09 18:36:51 +01:00
}
char *read_socket(int socket)
{
FILE *opened = why2_fdopen(socket, "r"); //OPEN socket
long content_size;
char *content;
//COUNT content_size
fseek(opened, 0, SEEK_END);
content_size = ftell(opened);
rewind(opened); //REWIND
//ALLOCATE
content = why2_calloc(content_size, sizeof(char));
if (fread(content, content_size, 1, opened) != 1) die("Reading socket failed!");
//DEALLOCATION
why2_deallocate(opened);
return content;
2023-02-09 09:09:26 +01:00
}