example programs from man getaddrinfo

master
Flavien Haas 5 years ago
parent c78915dcca
commit 3850a32c66

@ -1,96 +1,92 @@
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h>
#include <unistd.h> #include <unistd.h>
#include <arpa/inet.h> #include <string.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[]) { #define BUF_SIZE 500
struct sockaddr_in adresse;
int sock;
char buffer [LG_BUFFER]; int
int nb_lus; main(int argc, char *argv[])
{
struct addrinfo hints;
struct addrinfo *result, *rp;
int sfd, s, j;
size_t len;
ssize_t nread;
char buf[BUF_SIZE];
if (argc != 3){ if (argc < 3) {
perror("Nombre d'arguments invalides, vous devez entrer deux arguments"); fprintf(stderr, "Usage: %s host port msg...\n", argv[0]);
exit(-1); exit(EXIT_FAILURE);
} }
/* Obtain address(es) matching host/port */
// Serveur auquel on se connecte memset(&hints, 0, sizeof(struct addrinfo));
//char * hote = "127.0.0.1"; hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
char * hote = argv[1]; hints.ai_socktype = SOCK_DGRAM; /* Datagram socket */
hints.ai_flags = 0;
hints.ai_protocol = 0; /* Any protocol */
// Port du serveur sur lequel on se connecte0 s = getaddrinfo(argv[1], argv[2], &hints, &result);
//int port = 1234; if (s != 0) {
int port = atoi(argv[2]); fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s));
exit(EXIT_FAILURE);
struct hostent * hostent; }
struct servent * servent;
// Vider la structure adresse /* getaddrinfo() returns a list of address structures.
memset(&adresse, 0, sizeof(struct sockaddr_in)); Try each address until we successfully connect(2).
If socket(2) (or connect(2)) fails, we (close the socket
and) try the next address. */
// Donner l'adresse du serveur à la structure adresse for (rp = result; rp != NULL; rp = rp->ai_next) {
if (inet_aton(hote, & (adresse.sin_addr)) == 0) { sfd = socket(rp->ai_family, rp->ai_socktype,
if ((hostent = gethostbyname(hote)) == NULL) { rp->ai_protocol);
printf("Erreur : hote %s inconnu \n", hote); if (sfd == -1)
return -1; continue;
}
adresse.sin_addr.s_addr = ((struct in_addr *) (hostent->h_addr))->s_addr;
}
// Donner un numero de port à la structure adresse if (connect(sfd, rp->ai_addr, rp->ai_addrlen) != -1)
adresse.sin_port = htons(port); break; /* Success */
// Donner la famille de socket à la structure adresse close(sfd);
adresse.sin_family = AF_INET; }
// Créer la socket nommée sock if (rp == NULL) { /* No address succeeded */
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0 ) { fprintf(stderr, "Could not connect\n");
printf("Erreur : socket\n");
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
// Etablir la connexion avec le serveur freeaddrinfo(result); /* No longer needed */
if(connect(sock, (struct sockaddr *) & adresse, sizeof (struct sockaddr_in)) < 0 ) {
printf("Erreur : socket");
return -1;
}
while (1) { /* Send remaining command-line arguments as separate
// Lecture du clavier datagrams, and read responses from server */
if (fgets(buffer, 256, stdin) == NULL)
break;
if (buffer[strlen(buffer) - 1] == '\n') for (j = 3; j < argc; j++) {
buffer[strlen(buffer) - 1] = '\0'; len = strlen(argv[j]) + 1;
/* +1 for terminating null byte */
// Ecriture des données sur la socket if (len + 1 > BUF_SIZE) {
if (write(sock, buffer, strlen(buffer)) < 0 ) { fprintf(stderr,
printf("Erreur : write\n"); "Ignoring long message in argument %d\n", j);
break; continue;
} }
// Lecture de la réponse du serveur if (write(sfd, argv[j], len) != len) {
if ((nb_lus = read(sock, buffer, LG_BUFFER)) == 0 ) { fprintf(stderr, "partial/failed write\n");
break; exit(EXIT_FAILURE);
} }
if (nb_lus < 0) { nread = read(sfd, buf, BUF_SIZE);
printf("Erreur : read\n"); if (nread == -1) {
break; perror("read");
exit(EXIT_FAILURE);
} }
// Affichage de données recues, variable buffer printf("Received %ld bytes: %s\n", (long) nread, buf);
printf("%s\n", buffer);
} }
return EXIT_SUCCESS; exit(EXIT_SUCCESS);
} }

Binary file not shown.

@ -1,168 +1,91 @@
#define _GNU_SOURCE #include <sys/types.h>
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h>
#include <unistd.h> #include <unistd.h>
#include <arpa/inet.h> #include <string.h>
#include <netdb.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h> #include <sys/socket.h>
#include <netdb.h>
int cree_socket_stream (const char * nom_hote, const int num_port, const char * nom_proto); #define BUF_SIZE 500
int affiche_adresse_socket (int sock);
int serveur_tcp (void);
void traite_connexion (int sock);
int cree_socket_stream (const char * nom_hote, const int num_port, const char * nom_proto){
int sock;
struct sockaddr_in adresse;
struct hostent * hostent = NULL;
struct protoent * protoent = NULL;
if (nom_hote != NULL) {
if ((hostent = gethostbyname(nom_hote)) == NULL) {
printf("Erreur : gethostbyname\n");
return -1;
}
}
if ((protoent = getprotobyname(nom_proto)) == NULL) {
printf("Erreur : getprotobyname\n");
return -1;
}
// Créer la socket nommée sock
if((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0 ) {
printf("Erreur : socket");
return -1;
}
// Mise à 0 de la structure adresse
memset(& adresse, 0, sizeof(struct sockaddr_in));
// Donner la famille de socket dans la structure adresse
adresse.sin_family = AF_INET;
adresse.sin_port = num_port;
// Donner un numero de port à la structure adresse
if (num_port > 1024) {
adresse.sin_port = htons(num_port);
}
else {
adresse.sin_port = htons(0);
}
// Donner l'adresse du serveur à la structure adresse
if (hostent != NULL) {
adresse.sin_addr.s_addr = ((struct in_addr *) (hostent->h_addr))->s_addr;
}
else {
adresse.sin_addr.s_addr = htonl(INADDR_ANY);
}
// Pattacher un port a la socket sock
if (bind(sock, (struct sockaddr *) & adresse, sizeof(struct sockaddr_in)) < 0) {
close(sock);
printf("Erreur : bind\n");
return -1;
}
return sock;
}
int affiche_adresse_socket (int sock) {
struct sockaddr_in adresse;
socklen_t longueur;
longueur = sizeof(struct sockaddr_in); int
main(int argc, char *argv[])
{
struct addrinfo hints;
struct addrinfo *result, *rp;
int sfd, s;
struct sockaddr_storage peer_addr;
socklen_t peer_addr_len;
ssize_t nread;
char buf[BUF_SIZE];
if (getsockname(sock, & adresse, & longueur) < 0) { if (argc != 2) {
printf("Erreur : getsockname\n"); fprintf(stderr, "Usage: %s port\n", argv[0]);
return -1; exit(EXIT_FAILURE);
}
printf ("IP = %s, Port = %u \n", inet_ntoa(adresse.sin_addr), ntohs(adresse.sin_port));
return 0;
} }
int serveur_tcp (void) { memset(&hints, 0, sizeof(struct addrinfo));
int sock_contact; // Socket créée du côté du serveur hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
int sock_connectee; // Socket du côté du client qui se connecte hints.ai_socktype = SOCK_DGRAM; /* Datagram socket */
struct sockaddr_in adresse; hints.ai_flags = AI_PASSIVE; /* For wildcard IP address */
socklen_t longueur; hints.ai_protocol = 0; /* Any protocol */
hints.ai_canonname = NULL;
longueur = sizeof(struct sockaddr_in); hints.ai_addr = NULL;
hints.ai_next = NULL;
// Appeler la fonction cree_socket_stream() pour créer la socket nommée socket_contact
// Choisir : nom de l'hote, le num du port, le protocole
sock_contact = cree_socket_stream("0.0.0.0", 1234, "tcp"); s = getaddrinfo(NULL, argv[1], &hints, &result);
if (s != 0) {
if (sock_contact < 0) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s));
return -1; exit(EXIT_FAILURE);
} }
// Placer le serveur en écoute sur la socket nommée sock_contact /* getaddrinfo() returns a list of address structures.
listen(sock_contact, 5); Try each address until we successfully bind(2).
If socket() (or bind()) fails, we (close the socket
printf("Mon adresse >> "); and) try the next address. */
affiche_adresse_socket(sock_contact);
while (1) { for (rp = result; rp != NULL; rp = rp->ai_next) {
// tester si un client se connecte : appel accept() bloquant sfd = socket(rp->ai_family, rp->ai_socktype,
// Le retour de accept() est une nouvelle socket nommé sock_connectee rp->ai_protocol);
// avec laquelle l'échange avec le client aura lieu if (sfd == -1)
continue;
sock_connectee = accept(sock_contact, & adresse, & longueur); if (bind(sfd, rp->ai_addr, rp->ai_addrlen) == 0)
break; /* Success */
if (sock_connectee < 0) { close(sfd);
printf("Erreur : accept\n");
return -1;
} }
printf("Nouveau client\n"); if (rp == NULL) { /* No address succeeded */
fprintf(stderr, "Could not bind\n");
switch (fork()) { exit(EXIT_FAILURE);
case 0 : // Code du fils
close(sock_contact);
traite_connexion(sock_connectee);
exit(EXIT_SUCCESS);
case -1 :
printf("Erreur : fork\n");
return -1;
default : // Code du pere
close(sock_connectee);
}
}
return 0;
} }
void traite_connexion (int sock){ freeaddrinfo(result); /* No longer needed */
char buffer[256];
int longueur;
while (1) { /* Read datagrams and echo them back to sender */
// Lire la socket et récupérer le nombre d'octets lus dans la variable longueur
longueur = read(sock, buffer, 256);
if (longueur < 0) { for (;;) {
printf("Erreur : read\n"); peer_addr_len = sizeof(struct sockaddr_storage);
exit(EXIT_SUCCESS); nread = recvfrom(sfd, buf, BUF_SIZE, 0,
} (struct sockaddr *) &peer_addr, &peer_addr_len);
if (nread == -1)
continue; /* Ignore failed request */
if (longueur == 0) { char host[NI_MAXHOST], service[NI_MAXSERV];
break;
}
printf("J'ai lu %d bytes\n",longueur); s = getnameinfo((struct sockaddr *) &peer_addr,
// Pour le client telnet : peer_addr_len, host, NI_MAXHOST,
//buffer[longueur-2] = '\0'; service, NI_MAXSERV, NI_NUMERICSERV);
if (s == 0)
printf("Received %ld bytes from %s:%s\n",
(long) nread, host, service);
else
fprintf(stderr, "getnameinfo: %s\n", gai_strerror(s));
// Ecrire la variable buffer sur la socket if (sendto(sfd, buf, nread, 0,
write(sock, buffer, longueur); (struct sockaddr *) &peer_addr,
peer_addr_len) != nread)
fprintf(stderr, "Error sending response\n");
} }
close(sock);
}
int main (int argc, char * argv[]) {
return serveur_tcp();
} }

Binary file not shown.
Loading…
Cancel
Save