udp_echo_client.c

Go to the documentation of this file.
00001 /*
00002  * Copyright 2002,2003 Sony Corporation 
00003  *
00004  * Permission to use, copy, modify, and redistribute this software for
00005  * non-commercial use is hereby granted.
00006  *
00007  * This software is provided "as is" without warranty of any kind,
00008  * either expressed or implied, including but not limited to the
00009  * implied warranties of fitness for a particular purpose.
00010  */
00011 
00012 #include <stdio.h>
00013 #include <string.h>
00014 #include <sys/types.h>
00015 #include <sys/socket.h>
00016 #include <netinet/in.h>
00017 #include <netdb.h>
00018 
00019 #define PORT     54321
00020 #define BUFSIZE  512
00021 
00022 main(int argc, char **argv)
00023 {
00024     struct sockaddr_in  addr;
00025     struct hostent      *hp;
00026     int    fd;
00027     int    len;
00028     int    sizeof_addr;
00029     char   buf[BUFSIZE*2];
00030     int    ret;
00031 
00032     if (argc != 2){
00033         printf("Usage: udp_echo_client hostname\n");
00034         exit(1);
00035     }
00036 
00037     /*
00038      * Get a datagram socket (udp)
00039      */
00040     if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
00041         perror("socket");
00042         exit(1);
00043     }
00044 
00045     if ((hp = gethostbyname(argv[1])) == NULL) {
00046         perror("gethostbyname");
00047         exit(1);
00048     }
00049 
00050     memset((void*)&addr, 0, sizeof(addr));
00051     memcpy(&addr.sin_addr, hp->h_addr, hp->h_length);
00052 
00053     addr.sin_family = AF_INET;
00054     addr.sin_port = htons(PORT);
00055 
00056     printf("Enter message to AIBO>");
00057     while (fgets(buf, BUFSIZE, stdin) != NULL) {
00058         len = strlen(buf) + 1;
00059         
00060         /*
00061          * Send a datagram to the server
00062          */
00063         if (sendto(fd, buf, len, 0, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
00064             perror("sendto");
00065             close(fd);
00066             exit(1);
00067         }
00068 
00069         /*
00070          * Receive a datagram back
00071          */
00072         sizeof_addr = sizeof(addr);
00073         ret = recvfrom(fd, buf, sizeof(buf), 0 , (struct sockaddr *)&addr, &sizeof_addr);
00074         if (ret < 0) {
00075             perror("recvfrom");
00076             close(fd);
00077             exit(1);
00078         }
00079 
00080         buf[ret] = '\0';
00081         printf("Receive from AIBO : %s", buf);
00082         printf("Enter message to AIBO>");
00083     }
00084 
00085     close(fd);
00086     exit(0);
00087 }

Generated on Sun Dec 2 23:04:31 2007 for openSDK by  doxygen 1.3.9.1