test makefile added
[my-code/ivac.git] / stream.c
1 /* stream.c - streaming server
2  *
3  * author: hackbard
4  *
5  */
6
7 #include <stdio.h>
8 #include <stdlib.h>
9
10 /* memset */
11 #include <string.h>
12
13 /* socket and bind stuff */
14 #include <sys/types.h>
15 #include <sys/socket.h>
16
17 /* sockkaddr_in */
18 #include <netinet/in.h>
19
20 /* inet_ntoa ... */
21 #include <arpa/inet.h>
22
23 /* errno stuff ... */
24 #include <errno.h>
25
26 /* read, close */
27 #include <unistd.h>
28
29 /* defines ... */
30 #define MAX_SIZE 1000
31
32 int main(int argc, char *argv[]) {
33   int listen_fd, send_fd;
34   struct sockaddr_in local_addr, remote_addr;
35   socklen_t remote_addr_len;
36   int send_bytes, read_bytes;
37
38   if(argc!=2) {
39     printf("usage: %s <port>\n",argv[0]);
40     exit(1);
41   }
42
43   if((listen_fd=socket(AF_INET,SOCK_STREAM,0)) == -1) {
44     printf("can't open socket.\n");
45     exit(1);
46   }
47  
48   memset(&local_addr,0,sizeof(local_addr));
49   local_addr.sin_family=AF_INET;
50   local_addr.sin_port=htons(atoi(argv[1]));
51   local_addr.sin_addr.s_addr=htonl(INADDR_ANY);
52
53   if(bind(listen_fd,(struct sockaddr *)&local_addr,sizeof(local_addr))==-1) {
54     printf("unable to bind on port %d.\n",atoi(argv[1]));
55     perror("bind");
56     exit(1);
57   }
58
59   if(listen(listen_fd,1)==-1) {
60     printf("error listening on port %d.\n",atoi(argv[1]));
61     exit(1);
62   }
63
64   remote_addr_len=sizeof(remote_addr); 
65   if((send_fd=accept(listen_fd,(struct sockaddr *)&remote_addr,
66   &remote_addr_len))!=-1) {
67     printf("accepting connection from %s port %d.\n",
68     inet_ntoa(remote_addr.sin_addr),
69     ntohs(remote_addr.sin_port));
70
71       /* send stuff .... */
72       read_bytes=1;
73       while(read_bytes>0) {
74         unsigned char buf[MAX_SIZE];
75         read_bytes=read(0,buf,sizeof(buf));
76         send_bytes=send(send_fd,buf,read_bytes,0);
77       }
78
79       close(send_fd);
80       close(listen_fd);
81       printf("connection closed ...\n");
82       printf("%d from %d total bytes sent.\n",send_bytes,read_bytes);
83   }
84   return 0;
85 }