sysdis-tp/client.c

118 lines
3.1 KiB
C

#include "client.h"
int main(int argc, char* argv[]){
/* [1] Initialisation
=========================================================*/
/* (1) Socket information */
// Server information
struct hostent *server_host;
// Server socket address
static struct sockaddr_in server_addr;
// Server socket address length
socklen_t sock_len;
// Local socket
int sock;
/* (2) Misc. information */
// Response
char *msg = "some message";
// Reception buffer
char buffer[BUFSIZE];
// Will contain the response
char *response;
// Will contain the length of received/sent data
int nb_bytes;
/* [2] UPD socket creation
=========================================================*/
/* (1) Socket initialization */
sock = socket(AF_INET, SOCK_DGRAM, 0);
/* (1-) Manage error */
if( sock == -1 ){
perror("erreur création socket");
exit(1);
}
/* (2) Get host information */
server_host = gethostbyname("localhost");
/* (2-) Manage error */
if( server_host == NULL ){
perror("erreur adresse serveur");
exit(1);
}
/* (3) Create destination socket */
bzero(&server_addr, sizeof(struct sockaddr_in)); // clean @server_addr struct before updating
server_addr.sin_family = AF_INET; // set server addr family (ipv4)
server_addr.sin_port = htons(4000); // set server port
memcpy( &server_addr.sin_addr.s_addr, // ) set host ipv4 addr
/* ( */ server_host->h_addr, // )
/* ( */ server_host->h_length );
/* [3] Send message
=========================================================*/
// calculate server id struct size
sock_len = sizeof(struct sockaddr_in);
/* (1) Send message to server (identified by <sockaddr_in>) */
nb_bytes = sendto( sock, // ) socket
/* ( */ msg, // ) buffer
/* ( */ strlen(msg) + 1, // ) buffer size
/* ( */ 0, // ) flags
/* ( */ (struct sockaddr*) &server_addr, // ) server identifier
/* ( */ sock_len ); // identifier size
/* (2) Check if send succesfully */
if( nb_bytes == -1 ){
perror("erreur envoi message");
exit(1);
}
// log
printf("paquet envoyé, nb_bytes = %d\n",nb_bytes);
/* [4] Wait for response
=========================================================*/
nb_bytes = recvfrom( sock, // ) socket
/* ( */ buffer, // ) receive buffer
/* ( */ BUFSIZE, // ) buffer size
/* ( */ 0, // ) flags
/* ( */ (struct sockaddr*) &server_addr, // ) server identifier
/* ( */ &sock_len ); // identifier size
/* (2) Check if received successfully (and consistently) */
if( nb_bytes == -1 ){
perror("erreur réponse serveur");
exit(1);
}
/* (3) Copy response into var */
response = (char *) malloc(nb_bytes * sizeof(char));
memcpy(response, buffer, nb_bytes);
/* (4) log */
printf("response recue du serveur : %s\n",response);
/* [5] Close socket
=========================================================*/
close(sock);
return 0;
}