-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsocket-select.c
117 lines (93 loc) · 2.62 KB
/
socket-select.c
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
struct addrinfo hints;
int rv;
struct addrinfo *servinfo, *ptr;
int sock;
char buffer[1024 + 1];
fd_set rfds;
struct timeval tv;
int retval;
if (argc != 4)
{
fprintf(stderr, "usage: %s <domain> <port> <nickname>\n", argv[0]);
exit(EXIT_FAILURE);
}
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
hints.ai_socktype = SOCK_STREAM; /* TCP */
if ((rv = getaddrinfo(argv[1], argv[2], &hints, &servinfo)) != 0)
{
fprintf(stderr, "getaddrinfo() failed : %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
// boucle sur les résultats, crée la socket et se connect
for (ptr = servinfo; ptr != NULL; ptr = ptr->ai_next)
{
if ((sock = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol)) == -1)
{
fprintf(stderr, "socket() failed : %s\n", strerror(errno));
continue;
}
if (connect(sock, ptr->ai_addr, ptr->ai_addrlen) == -1)
{
fprintf(stderr, "connect() failed : %s\n", strerror(errno));
close(sock);
continue;
}
break;
}
if (ptr == NULL)
{
fprintf(stderr, "info: unable to connect\n");
exit(EXIT_FAILURE);
}
freeaddrinfo(servinfo);
printf("info: connected !\n");
sprintf(buffer, "NICK %s\r\nUSER %s 0 * :%s\r\n", argv[3], argv[3], argv[3]);
if (send(sock, buffer, strlen(buffer), 0) == -1)
{
fprintf(stderr, "send() failed : %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
for (;;)
{
FD_ZERO(&rfds);
FD_SET(sock, &rfds);
tv.tv_sec = 8;
tv.tv_usec = 0;
retval = select(sock + 1, &rfds, NULL, NULL, &tv);
if (retval < 0)
{
fprintf(stderr, "select() failed : %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
if (retval > 0)
{
rv = recv(sock, buffer, 1024, 0);
if (rv == 0) break;
if (rv == -1)
{
fprintf(stderr, "recv() failed : %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
buffer[rv] = 0;
printf("%s", buffer);
}
else
{
printf("info: aucune donnée dans la socket\n");
}
}
close(sock);
return 0;
}