client.c
1.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <poll.h>
#define MAX_BUFF 100
int connexionServeur(char* host, char* service)
{
int sock_fd;
struct addrinfo precisions, *resultat=NULL, *origine; // On stocke dans précisions nos besoins pour le socket, dans resultat l'adresse qui respectera les requêtes
memset(&precisions, 0, sizeof precisions);
precisions.ai_family = AF_UNSPEC;
precisions.ai_socktype = SOCK_STREAM;
if(getaddrinfo(host, service, &precisions, &origine)<0) { fprintf(stderr, "Erreur getaddrinfo\n"); return(-1); }
int n=0;
for(struct addrinfo* i=origine; i!=NULL && resultat==NULL; i=i->ai_next)
{
printf("%d - ", n);
if(i->ai_family==AF_INET)
{
resultat=i;
printf("Test : %d", origine->ai_addrlen);
}
printf("\n");
n++;
}
struct sockaddr_in* test=(struct sockaddr_in*)(resultat->ai_addr);
printf("Addr : %x\n", test->sin_addr.s_addr);
if((sock_fd=socket(resultat->ai_family, resultat->ai_socktype, resultat->ai_protocol))<0) { fprintf(stderr, "Erreur socket\n"); return(-1); }
if(connect(sock_fd, resultat->ai_addr, resultat->ai_addrlen) < 0) return(-1);
freeaddrinfo(origine);
return sock_fd;
}
int main(void)
{
char buffer[100];
int sock_fd = connexionServeur("localhost", "2020");
if(sock_fd<0) { fprintf(stderr, "Erreur connexionServeur\n"); return(-1); }
FILE* sockfd_stream = fdopen(sock_fd, "a+");
printf("State sock : %p\n", sockfd_stream);
for(int i=0; i<10; i++)
{
fprintf(sockfd_stream, "YES !!!\n");
//fprintf(sockfd_stream, "EXIT\n");
fgets(buffer, 100, sockfd_stream);
}
fprintf(sockfd_stream, "EXIT\n");
fclose(sockfd_stream);
shutdown(sock_fd, SHUT_RDWR);
return 0;
}