sysdis-tp/server.c

125 lines
3.5 KiB
C

#include "server.h"
int main(int argc, char* argv[]){
/* [1] Initialisation
=========================================================*/
/* (1) Socket info */
// Server (local)
static struct sockaddr_in addr_server;
// Client
static struct sockaddr_in addr_client;
// Client identifier
struct hostent *host_client = NULL;
// Socket size
socklen_t sock_len;
char client_ip[20];
// Socket
int sock;
/* (2) Misc. information */
// response
char *response = "bien recu";
// reception buffer
char buffer[BUFSIZE];
// received buffer
char *received;
// length of received/sent data
int buf_len;
/* [2] Create socket
=========================================================*/
/* (1) Create socket */
sock = socket(AF_INET, SOCK_DGRAM, 0); // ipv4, udp, flags?
/* (1-) Manage error */
if( sock == -1 ){
perror("erreur création socket");
exit(1);
}
/* (2) Set socket information */
bzero(&addr_server, sizeof(struct sockaddr_in));
addr_server.sin_family = AF_INET; // ipv4
addr_server.sin_port = htons(4000); // port: 4000
addr_server.sin_addr.s_addr = htonl(INADDR_ANY); //
/* (3) Bind socket to local port */
int bounded = bind( sock, // ) socket
/* ( */ (struct sockaddr*)&addr_server, // ) filled with address
/* ( */ sizeof(addr_server) ); // length of struct
/* (3-) Manage error */
if( bounded == -1 ){
perror("erreur bind");
exit(1);
}
/* [3] Wait for client message
=========================================================*/
// set socket length
sock_len = sizeof(struct sockaddr_in);
/* (1) Wait for message */
buf_len = recvfrom(sock, // ) socket
/* ( */ buffer, // ) buffer
/* ( */ BUFSIZE, // ) buffer length
/* ( */ 0, // ) flags
/* ( */ (struct sockaddr *)&addr_client, // ) client addr (filled)
/* ( */ &sock_len );
/* (1-) Manage error */
if( buf_len == -1 ){
perror("erreur réception paquet");
exit(1);
}
// Get client ip
inet_ntop(AF_INET, &(addr_client.sin_addr), client_ip, 20);
/* (2) Fetch client information */
// récupère nom de la machine émettrice des données
host_client = gethostbyaddr( &addr_client.sin_addr, // ) client addr (filled)
/* ( */ sizeof(struct in_addr), // ) sizeof addr
/* ( */ AF_INET ); // ipv4
/* (2-) Manage error */
if( host_client == NULL ){
perror("erreur gethostbyaddr");
exit(1);
}
/* (3) Store message */
received = (char *) malloc(buf_len * sizeof(char));
memcpy(received, buffer, buf_len);
printf( "recu message %s de %s:%d\n", received, client_ip, ntohs(addr_client.sin_port) );
/* [4] Send response
=========================================================*/
/* (1) Send response */
buf_len = sendto(sock, // ) socket
/* ( */ response, // ) response
/* ( */ strlen(response)+1, // ) response length
/* ( */ 0, // ) flags
/* ( */ (struct sockaddr*) &addr_client, // ) client identifier
/* ( */ sock_len ); // identifier length
/* (1-) Manage error */
if( buf_len == -1 ){
perror("erreur envoi réponse");
exit(1);
}
/* [5] Close socket
=========================================================*/
close(sock);
}