push sockt&epoll samples
[socket_samples.git] / server_udp.c
blob5e79f7f846d0ee7ef2fe915d46309ebba51f3b21
1 /* Creates a datagram server. The port
2 number is passed as an argument. This
3 server runs forever */
5 #include <sys/types.h>
6 #include <stdlib.h>
7 #include <unistd.h>
8 #include <sys/socket.h>
9 #include <netinet/in.h>
10 #include <string.h>
11 #include <netdb.h>
12 #include <stdio.h>
14 void error(const char *msg)
16 perror(msg);
17 exit(0);
20 int main(int argc, char *argv[])
22 int sock, length, n;
23 socklen_t fromlen;
24 struct sockaddr_in server;
25 struct sockaddr_in from;
26 char buf[1024];
28 if (argc < 2) {
29 fprintf(stderr, "ERROR, no port provided\n");
30 exit(0);
33 sock=socket(AF_INET, SOCK_DGRAM, 0);
34 if (sock < 0) error("Opening socket");
35 length = sizeof(server);
36 bzero(&server,length);
37 server.sin_family=AF_INET;
38 server.sin_addr.s_addr=INADDR_ANY;
39 server.sin_port=htons(atoi(argv[1]));
40 if (bind(sock,(struct sockaddr *)&server,length)<0)
41 error("binding");
42 fromlen = sizeof(struct sockaddr_in);
43 while (1) {
44 n = recvfrom(sock,buf,1024,0,(struct sockaddr *)&from,&fromlen);
45 if (n < 0) error("recvfrom");
46 write(1,"Received a datagram: ",21);
47 write(1,buf,n);
48 n = sendto(sock,"Got your message\n",17,
49 0,(struct sockaddr *)&from,fromlen);
50 if (n < 0) error("sendto");
52 return 0;