/* * Simple ECHO udp client * usage: clientechoudp host message * (c)2013 JBY */ #include <sys/socket.h> #include <netinet/in.h> #include <stdio.h> #include <stdlib.h> #include <netdb.h> #include <strings.h> #include <unistd.h> #define PORT 5678 int main(int argc,char *argv[]) { struct sockaddr_in addrto, addrfrom; int sock; char tampon[256]; struct hostent *hent; if (argc<3) { fprintf(stderr,"usage: %s host message\n",argv[0]); exit(1); } hent = gethostbyname(argv[1]); if (hent==NULL) { fprintf(stderr,"%s: host %s unknown\n",argv[0],argv[1]); exit(1); } sock = socket(PF_INET,SOCK_DGRAM,0); // Protocol family if (sock==-1) { perror("socket: "); exit(1); } /* BEGINNING OF OPTIONAL CODE inet sockets are 'auto-bound' */ addrfrom.sin_family = AF_INET; // Address family addrfrom.sin_port = htons(0); // Any suitable port addrfrom.sin_addr.s_addr = htonl(INADDR_ANY); // Any address if (bind(sock,(struct sockaddr *)(&addrfrom),sizeof(addrfrom))==-1) { perror("bind: "); close(sock); exit(1); } /* END OF OPTIONAL CODE */ addrto.sin_family = hent->h_addrtype; // destination from db memcpy(&(addrto.sin_addr.s_addr),hent->h_addr_list[0],hent->h_length); addrto.sin_port = htons(PORT); // fixed port strcpy(tampon,argv[2]); if (sendto(sock,tampon,256,0,(struct sockaddr *)(&addrto),sizeof(addrto))==-1) { perror("sendto: "); close(sock); exit(1); } if (strcmp(tampon,"quit")) { if (recv(sock,tampon,256,0)==-1) { perror("recv:"); close(sock); exit(1); } printf("Recu : %s\n",tampon); } close(sock); return 0; }