annotate resources/network/udp-server.c @ 427:fd948111f8ea prerelease

Compatibility: mingw's default date format is not parsed correctly by Debian; stat is not necessarily available
author Giulio Moro <giuliomoro@yahoo.it>
date Thu, 16 Jun 2016 18:09:59 +0100
parents 8c7f537d0a21
children fb56681ab1d6
rev   line source
giuliomoro@24 1 /* Creates a datagram server. The port
giuliomoro@24 2 number is passed as an argument. This
giuliomoro@24 3 server runs forever */
giuliomoro@24 4
giuliomoro@24 5 #include <sys/types.h>
giuliomoro@24 6 #include <stdlib.h>
giuliomoro@24 7 #include <unistd.h>
giuliomoro@24 8 #include <sys/socket.h>
giuliomoro@24 9 #include <netinet/in.h>
giuliomoro@24 10 #include <string.h>
giuliomoro@24 11 #include <netdb.h>
giuliomoro@24 12 #include <stdio.h>
giuliomoro@24 13
giuliomoro@24 14 void error(const char *msg)
giuliomoro@24 15 {
giuliomoro@24 16 perror(msg);
giuliomoro@24 17 exit(0);
giuliomoro@24 18 }
giuliomoro@24 19
giuliomoro@24 20 int main(int argc, char *argv[])
giuliomoro@24 21 {
giuliomoro@24 22 int sock, length, n;
giuliomoro@24 23 socklen_t fromlen;
giuliomoro@24 24 struct sockaddr_in server;
giuliomoro@24 25 struct sockaddr_in from;
giuliomoro@93 26 float buf[2048];
giuliomoro@93 27 int i=0;
giuliomoro@93 28 for(i=0; i<2048; i++){
giuliomoro@93 29 buf[i]=0;
giuliomoro@93 30 }
giuliomoro@24 31 if (argc < 2) {
giuliomoro@24 32 fprintf(stderr, "ERROR, no port provided\n");
giuliomoro@24 33 exit(0);
giuliomoro@24 34 }
giuliomoro@24 35
giuliomoro@24 36 sock=socket(AF_INET, SOCK_DGRAM, 0);
giuliomoro@24 37 if (sock < 0) error("Opening socket");
giuliomoro@24 38 length = sizeof(server);
giuliomoro@24 39 bzero(&server,length);
giuliomoro@24 40 server.sin_family=AF_INET;
giuliomoro@24 41 server.sin_addr.s_addr=INADDR_ANY;
giuliomoro@24 42 server.sin_port=htons(atoi(argv[1]));
giuliomoro@24 43 if (bind(sock,(struct sockaddr *)&server,length)<0)
giuliomoro@24 44 error("binding");
giuliomoro@24 45 fromlen = sizeof(struct sockaddr_in);
giuliomoro@24 46 while (1) {
giuliomoro@93 47 n = recvfrom(sock,buf,2048,0,(struct sockaddr *)&from,&fromlen);
giuliomoro@24 48 if (n < 0) error("recvfrom");
giuliomoro@93 49 printf("Received a datagram of size %d: \n", n);
giuliomoro@93 50 for(i=0; i<n/sizeof(float); i+=8)
giuliomoro@93 51 printf("[%05d]: %+f, %+f, %+f, %+f, %+f, %+f, %+f, %+f\n",i,buf[0+i],buf[1+i],buf[2+i],buf[3+i],buf[4+i],buf[5+i],buf[6+i],buf[7+i]);
giuliomoro@24 52 n = sendto(sock,"Got your message\n",17,
giuliomoro@24 53 0,(struct sockaddr *)&from,fromlen);
giuliomoro@24 54 if (n < 0) error("sendto");
giuliomoro@24 55 }
giuliomoro@24 56 return 0;
giuliomoro@24 57 }
giuliomoro@24 58