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
| nbDevice = 0;
// Effectue la connexion à tous les appareils
for(i = 0 ; i < 5 ; i++) {
struct in_addr i_addr;
struct sockaddr_in s_addr;
struct timeval tv;
fd_set myset;
long arg;
int rc, fd;
// Initialise l'appareil
Device[i].fdEnable = false;
Device[i].status = OFFLINE;
if(inet_aton(Device[i].adresseIp, &i_addr) == 0) {
exiterr(4);
}
// Création de la socket
s_addr.sin_addr.s_addr = i_addr.s_addr;
s_addr.sin_family = AF_INET;
s_addr.sin_port = htons(80);
fd = socket(PF_INET, SOCK_STREAM, 0);
if(fd >= 0) {
// Configuration non bloquante
arg = fcntl(fd, F_GETFL, NULL);
arg |= O_NONBLOCK;
fcntl(fd, F_SETFL, arg);
// Connexion
rc = connect(fd, (struct sockaddr *) &s_addr, sizeof(s_addr));
if (rc == -1) {
if(errno == EINPROGRESS) {
// Enregistre le File descriptor
Device[i].fd = fd;
Device[i].fdEnable = true;
nbDevice++;
}
}
}
}
// Attente des réponses des appareils
while(nbDevice) {
fd_set myset;
int nfds = 0;
long arg;
struct timeval tv;
// Initialise myset, avec tous les files descriptor en attente de réponse
FD_ZERO(&myset);
for(i = 0 ; i < 5 ; i++) {
if(Device[i].fdEnable) {
FD_SET(Device[i].fd, &myset);
nfds = MAX(nfds, Device[i].fd);
}
}
tv.tv_sec = 5;
tv.tv_usec = 0;
if (select(nfds+1, NULL, &myset, NULL, &tv) > 0) {
// Cherche l'appareil ayant répondu
for(i = 0 ; i < 5 ; i++) {
if(Device[i].fdEnable) {
if(FD_ISSET(Device[i].fd, &myset)) {
// Supprime la configuration non bloquante
arg = fcntl(Device[i].fd, F_GETFL, NULL);
arg = (~O_NONBLOCK);
fcntl(Device[i].fd, F_SETFL, arg);
close(Device[i].fd);
// Change le status de l'appareil
Device[i].status = ONLINE;
Device[i].fdEnable = false;
nbDevice--;
}
}
}
}
else {
// Timeout
nbDevice = 0;
}
} |
Partager