Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
2.6 kB
2
Indexable
Never
 // =========================== SERVER.H =====================================
 #include<sys/types.h>
 #include<sys/socket.h>
 #include<netdb.h>

 // ---------- OPEN SERVER SOCKET FUNCTION ---------
 int open_server_socket(){
 int server_socket;
int true = 1;

 // Deschidere socket
 // AF_INET - IPv4
 // SOCK_STREAM - conectare TCP
 server_socket = socket(AF_INET, SOCK_STREAM, 0);
 if(server_socket == -1){
 perror(" -> Socket-ul nu a fost deschis! \n");
 return 0;
 }
 puts(" -> Socket-ul a fost deschis!");

 // Optiune Socket
 // - server_socket - socketul utilizat
 // - SOL_SOCKET - pentru cine ii definita optiunea
 // - SO_REUSEADDR - permite socket-ului sa faca bind la o adresa si port deja
ilizate
 if(setsockopt(server_socket, SOL_SOCKET, SO_REUSEADDR, &true, sizeof(int)) == -1){
 perror(" -> Eroare la setarea optiuni \n");
 return 0;
 }

 return server_socket;

 }
 // ---------- END FUNCTION ---------

 // ---------- BIND SERVER SOCKET FUCNTION --------
 void bind_server_socket(int sock, int port){
 struct sockaddr_in serv_addr;

 serv_addr.sin_family = AF_INET; // IPv4
 serv_addr.sin_port = htons(port); // port
 serv_addr.sin_addr.s_addr = INADDR_ANY; //selectare automata a interfacei

 if(bind(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) == -1){
 perror(" -> Eroare bind socket! \n");
 }else{
 printf(" -> Bind OK pe portul %d \n ", port);
 }

 }
 // -------- END FUNCTION ---------

 // -------- START LISTEN FUNCTION -------
 void start_listen(int sock, int pending_con){
 if(listen(sock, pending_con) == -1){
 perror(" -> Eroare asteptare client! \n");
 }else{
 puts("\n Asteptare client ... \n");
 }

 }
 // --------- END FUNCTION --------

 // --------- ACCEPT CONNECTIONS FUNCTION ---------
 int accept_connections(int sock){
 struct sockaddr_storage their_addr;
 socklen_t addr_size;

 addr_size = sizeof their_addr;
 int accept_socket = accept(sock, (struct sockaddr *)&their_addr, &addr_size);
 if(accept_socket == -1){
 perror(" -> Conexiunea NU a fost acceptata \n");
 send(accept_socket, "Conexiunea NU a fost acceptata!\n", 100, 0);
 return 0;
 }else{
 puts(" -> Conexiune acceptata! ");
 send(accept_socket, "Conexiunea a fost acceptata! \n", 100, 0);
 return accept_socket;
 }
 }
 // ---------- END FUNCTION --------


 // --------- CHECK COMMAND --------
 int CheckCommand(char *buffer, char *command){

 if(buffer[0] == command[0] && buffer[1] == command[1] && buffer[2] == '#'){
 return 1;
 }
 else{
 return 0;
 }

 }
 // -------- END FUNCTION --------