You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
88 lines
1.9 KiB
C
88 lines
1.9 KiB
C
5 years ago
|
#include <stdio.h>
|
||
|
#include <stdlib.h>
|
||
|
#include <string.h>
|
||
|
#include <unistd.h>
|
||
|
#include <arpa/inet.h>
|
||
|
#include <netdb.h>
|
||
|
#include <netinet/in.h>
|
||
|
#include <sys/types.h>
|
||
|
#include <sys/socket.h>
|
||
|
|
||
|
#define LG_BUFFER 1024
|
||
|
|
||
|
int main (int argc, char * argv[]) {
|
||
|
struct sockaddr_in adresse;
|
||
|
int sock;
|
||
|
|
||
|
char buffer [LG_BUFFER];
|
||
|
int nb_lus;
|
||
|
|
||
|
// Serveur auquel on se connecte
|
||
|
char * hote = "127.0.0.1";
|
||
|
// Port du serveur sur lequel on se connecte
|
||
|
int port = 60000;
|
||
|
|
||
|
struct hostent * hostent;
|
||
|
struct servent * servent;
|
||
|
|
||
|
// Vider la structure adresse
|
||
|
memset(&adresse, 0, sizeof(struct sockaddr_in));
|
||
|
|
||
|
// Donner l'adresse du serveur à la structure adresse
|
||
|
if (inet_aton(hote, & (adresse.sin_addr)) == 0) {
|
||
|
if ((hostent = gethostbyname(hote)) == NULL) {
|
||
|
printf("Erreur : hote %s inconnu \n", hote);
|
||
|
return -1;
|
||
|
}
|
||
|
adresse.sin_addr.s_addr = ((struct in_addr *) (hostent->h_addr))->s_addr;
|
||
|
}
|
||
|
|
||
|
// Donner un numero de port à la structure adresse
|
||
|
adresse.sin_port = htons(port);
|
||
|
|
||
|
// Donner la famille de socket à la structure adresse
|
||
|
adresse.sin_family = AF_INET;
|
||
|
|
||
|
// Créer la socket nommée sock
|
||
|
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0 ) {
|
||
|
printf("Erreur : socket\n");
|
||
|
exit(EXIT_FAILURE);
|
||
|
}
|
||
|
|
||
|
// Etablir la connexion avec le serveur
|
||
|
if(connect(sock, (struct sockaddr *) & adresse, sizeof (struct sockaddr_in)) < 0 ) {
|
||
|
printf("Erreur : socket");
|
||
|
return -1;
|
||
|
}
|
||
|
|
||
|
while (1) {
|
||
|
// Lecture du clavier
|
||
|
if (fgets(buffer, 256, stdin) == NULL)
|
||
|
break;
|
||
|
|
||
|
if (buffer[strlen(buffer) - 1] == '\n')
|
||
|
buffer[strlen(buffer) - 1] = '\0';
|
||
|
|
||
|
// Ecriture des données sur la socket
|
||
|
if (write(sock, buffer, strlen(buffer)) < 0 ) {
|
||
|
printf("Erreur : write\n");
|
||
|
break;
|
||
|
}
|
||
|
|
||
|
// Lecture de la réponse du serveur
|
||
|
if ((nb_lus = read(sock, buffer, LG_BUFFER)) == 0 ) {
|
||
|
break;
|
||
|
}
|
||
|
|
||
|
if (nb_lus < 0) {
|
||
|
printf("Erreur : read\n");
|
||
|
break;
|
||
|
}
|
||
|
|
||
|
// Affichage de données recues, variable buffer
|
||
|
printf("%s\n", buffer);
|
||
|
}
|
||
|
|
||
|
return EXIT_SUCCESS;
|
||
|
}
|