Final assignment for the course "Real Time and Embedded Systems" of THMMY in AUTH university.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

56 lines
1.4 KiB

#include "helpers.h"
int create_socket(uint16_t port) {
int sock;
struct sockaddr_in socket_name;
// Creates the socket
sock = socket (PF_INET, SOCK_STREAM, 0); //TODO: check if PF_INET is the right one
if (sock < 0) {
perror("Couldn't create the socket.");
exit(EXIT_FAILURE);
}
// Gives the socket a name
socket_name.sin_family = AF_INET;
socket_name.sin_port = htons(port);
socket_name.sin_addr.s_addr = htonl(INADDR_ANY);
// Binds own address structure to socket
if (bind(sock, (struct sockaddr *) &socket_name, sizeof(socket_name)) < 0) {
perror("Couldn't bind the address structure to the socket.");
exit(EXIT_FAILURE);
}
return sock;
}
int read_from_client(int file_des, uint16_t max_line) {
char buffer[max_line];
int nbytes;
nbytes = read(file_des, buffer, sizeof(buffer));
if (nbytes < 0) {
perror("Couldn't read from client.");
exit(EXIT_FAILURE);
} else if (nbytes == 0)
// End-of-file
return -1;
else {
fprintf(stderr, "Server: got message: `%s'\n", buffer);
return 0;
}
}
void init_sockaddr(struct sockaddr_in *name, const char *hostname, uint16_t port) {
struct hostent *hostinfo;
name->sin_family = AF_INET;
name->sin_port = htons(port);
hostinfo = gethostbyname(hostname);
if (hostinfo == NULL) {
fprintf(stderr, "Unknown host %s.\n", hostname);
exit(EXIT_FAILURE);
}
name->sin_addr = *(struct in_addr *) hostinfo->h_addr_list[0];
}