feat: now able to retrieve client ip, especially useful for logs
This commit is contained in:
parent
8ec545e126
commit
9ecc9ed9a7
1 changed files with 19 additions and 4 deletions
|
|
@ -1,12 +1,12 @@
|
||||||
// === Definitions
|
// === Definitions
|
||||||
|
|
||||||
|
#include <netinet/in.h>
|
||||||
#define _POSIX_C_SOURCE 200112L
|
#define _POSIX_C_SOURCE 200112L
|
||||||
|
|
||||||
#define BUFFER_SIZE 1024
|
#define BUFFER_SIZE 1024
|
||||||
|
|
||||||
// === Includes
|
// === Includes
|
||||||
#include "server.h"
|
#include <arpa/inet.h>
|
||||||
|
|
||||||
#include <netdb.h>
|
#include <netdb.h>
|
||||||
#include <stdbool.h>
|
#include <stdbool.h>
|
||||||
#include <stddef.h>
|
#include <stddef.h>
|
||||||
|
|
@ -15,6 +15,7 @@
|
||||||
|
|
||||||
#include "../http/http.h"
|
#include "../http/http.h"
|
||||||
#include "../logger/errors.h"
|
#include "../logger/errors.h"
|
||||||
|
#include "server.h"
|
||||||
// #include "../logger/logs.h"
|
// #include "../logger/logs.h"
|
||||||
|
|
||||||
// === Static functions
|
// === Static functions
|
||||||
|
|
@ -92,6 +93,15 @@ static int get_socket(const char *hostname, const char *port)
|
||||||
// }
|
// }
|
||||||
// }
|
// }
|
||||||
|
|
||||||
|
// Retrieves client ipv4 address and stores it in res
|
||||||
|
// WARNING: res must be of size INET_ADDRSTRLEN
|
||||||
|
static void get_ip(struct sockaddr *client_addr, char *res)
|
||||||
|
{
|
||||||
|
// NOTE: exceptionally authorized cast
|
||||||
|
struct in_addr ipAddr = ((struct sockaddr_in *)client_addr)->sin_addr;
|
||||||
|
inet_ntop(AF_INET, &ipAddr, res, INET_ADDRSTRLEN);
|
||||||
|
}
|
||||||
|
|
||||||
// === Functions
|
// === Functions
|
||||||
|
|
||||||
void start_server(const char *host, const char *port)
|
void start_server(const char *host, const char *port)
|
||||||
|
|
@ -108,13 +118,18 @@ void start_server(const char *host, const char *port)
|
||||||
// Main loop
|
// Main loop
|
||||||
while (1)
|
while (1)
|
||||||
{
|
{
|
||||||
int client_fd = accept(server_socket, NULL, NULL);
|
struct sockaddr client_addr;
|
||||||
|
int client_fd = accept(server_socket, &client_addr, NULL);
|
||||||
if (client_fd == -1)
|
if (client_fd == -1)
|
||||||
continue;
|
continue;
|
||||||
|
|
||||||
// TODO handle signals to stop
|
// TODO handle signals to stop
|
||||||
|
|
||||||
handle_request(client_fd, "127.0.0.1");
|
// Get ip
|
||||||
|
char client_ip[INET_ADDRSTRLEN];
|
||||||
|
get_ip(&client_addr, client_ip);
|
||||||
|
|
||||||
|
handle_request(client_fd, client_ip);
|
||||||
// send_back(client_fd);
|
// send_back(client_fd);
|
||||||
close(client_fd);
|
close(client_fd);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue