Programmation Avancée en C


bind_ipv4.c

00001 #include <arpa/inet.h>
00002 #include <netinet/in.h>
00003 #include <stdio.h>
00004 #include <stdlib.h>
00005 #include <sys/socket.h>
00006 #include <sys/types.h>
00007 #include <unistd.h>
00008 
00009 #include "printtools.h"
00010 
00011 int main()
00012 {
00013         int sockfd;
00014         struct sockaddr_in server;
00015         server.sin_family      = AF_INET;
00016         server.sin_port        = 6666;
00017         server.sin_addr.s_addr = htonl(INADDR_ANY); // wildcard
00018 
00019         // Création d'une socket.
00020         if ((sockfd = socket(PF_INET, SOCK_STREAM, 0)) == -1) {
00021                 perror("[socket]");
00022                 exit(EXIT_FAILURE);
00023         }
00024         // Attachement à l'adresse serveur.
00025         if (bind(sockfd, (struct sockaddr *) &server, sizeof(server))) {
00026                 perror("[bind]");
00027                 exit(EXIT_FAILURE);
00028         }
00029         // ...
00030         print_ipv4(&server);
00031 
00032         // Test de getsockname.
00033         struct sockaddr_in server_info;
00034         socklen_t addrlen = sizeof(server_info);
00035         if (getsockname(sockfd, (struct sockaddr *)&server_info, &addrlen))
00036                 perror("[getsockname]");
00037         else print_ipv4(&server_info);
00038 
00039         close(sockfd);
00040         return EXIT_SUCCESS;
00041 }
00042