#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <fstream.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <stdio.h>
 
#include "ps5/server.h"

server::server(int port) {
    s = -1;
    s = socket(AF_INET, SOCK_STREAM, 0);
    if (s < 0) { perror("create socket"); exit(1); }

    struct sockaddr_in sa;
    sa.sin_family = AF_INET;
    sa.sin_addr.s_addr = INADDR_ANY;
    sa.sin_port = htons(port);
    if (0 > bind(s, (struct sockaddr*) &sa, sizeof(sa))) {
	perror ("bind socket");
	exit(1);
    }
    if (0 > listen(s, 4)) {
	perror ("listen socket");
	exit(1);
    }
}

int server::accept() {
    int new_s;
    for (;;) {
	new_s = ::accept(s, 0, 0);
	if (new_s >= 0) break;
	if (errno != EINTR) {
	    perror("accept");
	    exit(1);
	}
    }
    return new_s;
}

void server::close() {
    ::close(s);
}

int server::file_descriptor() {
    return s;
}
