added server
This commit is contained in:
parent
b65807dc10
commit
043c51c899
|
@ -0,0 +1,103 @@
|
|||
|
||||
#include <sys/types.h>
|
||||
#include <unistd.h>
|
||||
#include <stdlib.h>
|
||||
#include <signal.h>
|
||||
#include <stdbool.h>
|
||||
#include <stdio.h>
|
||||
#include <sys/socket.h>
|
||||
#include <netinet/in.h>
|
||||
#include <fcntl.h>
|
||||
|
||||
|
||||
bool shouldrun = true;
|
||||
int fd = -1;
|
||||
|
||||
void sighand(int sig) {
|
||||
shouldrun = false;
|
||||
close(fd);
|
||||
}
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
|
||||
|
||||
int port = 2223;
|
||||
|
||||
if(argc < 2) {
|
||||
fprintf(stderr, "Usage: %s <logfile> [port]", argv[0]);
|
||||
return 1;
|
||||
}
|
||||
|
||||
char* logfile = argv[1];
|
||||
|
||||
if(argc > 2) {
|
||||
port = atoi(argv[2]);
|
||||
}
|
||||
|
||||
//create socket
|
||||
fd = socket(AF_INET, SOCK_STREAM, 0);
|
||||
if(fd < 0) {
|
||||
fprintf(stderr, "could not create socket\n");
|
||||
return 1;
|
||||
}
|
||||
|
||||
//ignore errors
|
||||
setsockopt(fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &(int){1}, sizeof(int));
|
||||
|
||||
struct sockaddr_in bindaddr;
|
||||
bindaddr.sin_family = AF_INET;
|
||||
bindaddr.sin_addr.s_addr = INADDR_ANY;
|
||||
bindaddr.sin_port = htons( port );
|
||||
if(bind(fd, &bindaddr, sizeof(struct sockaddr_in))) {
|
||||
fprintf(stderr, "Bind failed\n");
|
||||
return 1;
|
||||
}
|
||||
|
||||
if(listen(fd, 5)) {
|
||||
fprintf(stderr, "listen failed\n");
|
||||
return 1;
|
||||
}
|
||||
|
||||
signal(SIGINT, sighand);
|
||||
|
||||
while(shouldrun) {
|
||||
struct sockaddr_in clientaddr;
|
||||
socklen_t caddrlen = 0;
|
||||
int client = accept(fd, (struct sockaddr *)&clientaddr, (socklen_t*)&caddrlen);
|
||||
if(client < 0) {
|
||||
fprintf(stderr, "accept failed\n");
|
||||
continue;
|
||||
}
|
||||
|
||||
//open THE file
|
||||
int file = open(logfile, O_RDONLY);
|
||||
if(file < 0) {
|
||||
fprintf(stderr, "Cannot open logfile\n");
|
||||
close(client);
|
||||
continue;
|
||||
}
|
||||
|
||||
//jump to the end
|
||||
lseek(file, -sizeof(time_t), SEEK_END);
|
||||
|
||||
//read
|
||||
time_t data;
|
||||
size_t readc = read(file, &data, sizeof(time_t));
|
||||
if(readc != sizeof(time_t)) {
|
||||
fprintf(stderr, "could not read logfile\n");
|
||||
close(file);
|
||||
close(client);
|
||||
continue;
|
||||
}
|
||||
|
||||
size_t writec = write(client, &data, sizeof(time_t));
|
||||
if(writec != sizeof(time_t)) {
|
||||
fprintf(stderr, "could not read logfile\n");
|
||||
}
|
||||
|
||||
close(file);
|
||||
close(client);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
Loading…
Reference in New Issue