sysdis-tp/client.c

112 lines
2.5 KiB
C

#include "client.h"
int main(int argc, char* argv[]){
/* [1] Initialization + arguments
=========================================================*/
/* (1) Socket information */
struct sockaddr_in server_addr; // server info
int sock, // socket
port; // chosen port
char hostname[24]; // chosen hostname
/* (2) Misc. information */
int bytes; // transfer count
char* to_send = (char*) malloc( sizeof(requete)+sizeof(int)+1 );
long to_recv;
requete request;
int param;
/* [2] Manage arguments
=========================================================*/
/* (1) Manage arguments count */
if( argc < 3 ){
printf("Missing arguments\nUsage: client hostname port [message]\n");
return 1;
}
/* (2) Manage @hostname argument */
if( strlen(argv[1]) > 24 || sscanf(argv[1], "%s", hostname) <= 0 ){
printf("argument error: hostname must be a string (max: 24 characters long)\n");
return 1;
}
/* (3) Manage port argument */
if( sscanf(argv[2], "%d", &port) <= 0 ){
printf("argument error: port must be a valid integer\n");
return 1;
}
/* (4) Manage optional @message argument */
if( argc >= 4 ){
if( strlen(argv[3]) > BUFSIZE || sscanf(argv[3], "%s", to_send) <= 0 ){
printf("argument error: message must be a string (max: %d characters long)\n", BUFSIZE);
return 1;
}
}else
strcpy(to_send, "client default message");
/* [3] Create TCP socket and get target data
=========================================================*/
sock = xconnect(hostname, port, &server_addr);
/* (1-) Manage error */
if( sock == -1 ){
perror("erreur connection server");
exit(1);
}
request.type = FACTO;
//size of the request isn't important
request.taille = sizeof(int);
param = 2;
memcpy(to_send,&request,sizeof(requete));
memcpy(to_send+sizeof(requete),&param,sizeof(int));
bytes = write(sock,to_send,sizeof(requete)+sizeof(int));
sleep(2);
param = 3;
memcpy(to_send+sizeof(requete),&param,sizeof(int));
bytes = write(sock,to_send,sizeof(requete)+sizeof(int));
if( bytes == -1 ){
perror("erreur envoi requete");
exit(1);
}
/* [5] Wait for response
=========================================================*/
/* (1) Wait for response */
bytes = recv(sock, &to_recv, sizeof(long),0);
/* (2) Check if received successfully (and consistently) */
if( bytes == -1 ){
perror("erreur réponse serveur");
exit(1);
}
/* (4) log */
printf("*** received : '%ld'\n", to_recv);
/* [6] Close socket
=========================================================*/
close(sock);
printf("Closing socket\n");
return 0;
}