#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( BUFSIZE * sizeof(char) ); char* to_recv = (char*) malloc( BUFSIZE * sizeof(char) ); /* [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 UPD socket and get target data =========================================================*/ sock = xconnect(hostname, port, &server_addr); /* (1-) Manage error */ if( sock == -1 ){ perror("erreur connection server"); exit(1); } /* [4] Send message =========================================================*/ /* (1) Send message to server */ bytes = xwrite(sock, to_send); /* (2) Check if send succesfully */ if( bytes == -1 ){ perror("erreur envoi message"); exit(1); } DEBUG&& printf("*** sent %d bytes\n", bytes); /* [5] Wait for response =========================================================*/ /* (1) Wait for response */ bytes = xread(sock, to_recv, BUFSIZE); /* (2) Check if received successfully (and consistently) */ if( bytes == -1 ){ perror("erreur réponse serveur"); exit(1); } /* (4) log */ printf("*** received : '%s'\n", to_recv); /* [6] Close socket =========================================================*/ close(sock); return 0; }