Mercurial > hg > beaglert
annotate resources/udp-server.c @ 24:ad5cd8dd99b3 bbb_network
UDP communication in place, pre-alpha
author | Giulio Moro <giuliomoro@yahoo.it> |
---|---|
date | Fri, 08 May 2015 11:12:13 +0100 |
parents | |
children |
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@24 | 26 char buf[1024]; |
giuliomoro@24 | 27 |
giuliomoro@24 | 28 if (argc < 2) { |
giuliomoro@24 | 29 fprintf(stderr, "ERROR, no port provided\n"); |
giuliomoro@24 | 30 exit(0); |
giuliomoro@24 | 31 } |
giuliomoro@24 | 32 |
giuliomoro@24 | 33 sock=socket(AF_INET, SOCK_DGRAM, 0); |
giuliomoro@24 | 34 if (sock < 0) error("Opening socket"); |
giuliomoro@24 | 35 length = sizeof(server); |
giuliomoro@24 | 36 bzero(&server,length); |
giuliomoro@24 | 37 server.sin_family=AF_INET; |
giuliomoro@24 | 38 server.sin_addr.s_addr=INADDR_ANY; |
giuliomoro@24 | 39 server.sin_port=htons(atoi(argv[1])); |
giuliomoro@24 | 40 if (bind(sock,(struct sockaddr *)&server,length)<0) |
giuliomoro@24 | 41 error("binding"); |
giuliomoro@24 | 42 fromlen = sizeof(struct sockaddr_in); |
giuliomoro@24 | 43 while (1) { |
giuliomoro@24 | 44 n = recvfrom(sock,buf,1024,0,(struct sockaddr *)&from,&fromlen); |
giuliomoro@24 | 45 if (n < 0) error("recvfrom"); |
giuliomoro@24 | 46 write(1,"Received a datagram: ",21); |
giuliomoro@24 | 47 write(1,buf,n); |
giuliomoro@24 | 48 n = sendto(sock,"Got your message\n",17, |
giuliomoro@24 | 49 0,(struct sockaddr *)&from,fromlen); |
giuliomoro@24 | 50 if (n < 0) error("sendto"); |
giuliomoro@24 | 51 } |
giuliomoro@24 | 52 return 0; |
giuliomoro@24 | 53 } |
giuliomoro@24 | 54 |