socket_Unix1_client.c
00001 #include <stdio.h>
00002 #include <stdlib.h>
00003 #include <unistd.h>
00004 #include <sys/types.h>
00005 #include <sys/socket.h>
00006 #include <netinet/in.h>
00007 #include <arpa/inet.h>
00008 #include <netdb.h>
00009 #include <string.h>
00010 #define __USE_MISC 1
00011 #include <sys/un.h>
00012
00013 #define TAILLE_MAX 256
00014
00015 void error(char * msg);
00016 void doit(int desc_sock, struct sockaddr_un * serv);
00017
00018
00019 #define CHEMIN_SERVEUR "/tmp/server.socket" // Chemin de la socket serveur.
00020
00021 int main(int argc, char* argv[])
00022 {
00023 char * chem_svr = CHEMIN_SERVEUR;
00024 struct sockaddr_un adr_svr;
00025
00026 switch (argc) {
00027 case 2: chem_svr = argv[1];
00028 case 1: break;
00029 default: fprintf(stderr, "Usage: %s [server_path]\n",argv[0]);
00030 return EXIT_FAILURE;
00031 }
00032
00033
00034 memset(&adr_svr, 0, sizeof(adr_svr));
00035 #ifndef __GLIBC__
00036 adr_svr.sun_len = sizeof(adr_svr);
00037 #endif
00038 adr_svr.sun_family = AF_LOCAL;
00039 strncpy(adr_svr.sun_path, chem_svr, sizeof(adr_svr.sun_path)-1);
00040 adr_svr.sun_path[sizeof adr_svr.sun_path - 1] = 0;
00041
00042
00043 int desc_sock = socket(AF_LOCAL,SOCK_STREAM,0);
00044 if (desc_sock == -1) error("[socket]");
00045
00046
00047 if (connect(desc_sock, (struct sockaddr *) &adr_svr, SUN_LEN(&adr_svr)))
00048 error("[connect]");
00049 doit(desc_sock, &adr_svr);
00050
00051
00052 close(desc_sock);
00053 return EXIT_SUCCESS;
00054 }
00055
00056
00057 void doit(int desc_sock, struct sockaddr_un * serv)
00058 {
00059 char requete[TAILLE_MAX] = "Luc, je suis ton père!";
00060 char reponse[TAILLE_MAX+1];
00061 size_t request_size = strlen(requete) + 1;
00062
00063 ssize_t n = send(desc_sock, requete, request_size, 0);
00064 if (n != request_size) error("[send]");
00065 printf("Requête envoyée à %s : <%s> (%ld octets)\n", serv->sun_path, requete, (long) n);
00066
00067 n = recv(desc_sock, reponse, TAILLE_MAX-1, 0);
00068 if (n < 0) error("[recv]");
00069 reponse[TAILLE_MAX] = '\0';
00070 printf("Réponse obtenue: <%s> (%ld octets)\n", reponse, (long) n);
00071 }
00072
00073 void error(char * msg)
00074 {
00075 perror(msg);
00076 exit(EXIT_FAILURE);
00077 }
00078
00079
00080
00081
00082
00083
00084
00085
00086
00087
00088
00089
00090
00091