added streaming support
[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
24 int main(int argc, char *argv[]) {
25   int listen_fd, send_fd;
26   struct sockaddr_in local_addr, *remote_addr;
27   int send_bytes, read_bytes;
28
29   if(argc!=2) {
30     printf("usage: %s <port>\n",argv[0]);
31     exit(1);
32   }
33
34   if(listen_fd=socket(AF_INET,SOCK_STREAM,0) == -1) {
35     printf("can't open socket.\n");
36     exit(1);
37   }
38   
39   local_addr.sin_family=AF_INET;
40   local_addr.sin_port=htons(atoi(argv[1]));
41   local_addr.sin_addr.s_addr=htonl(INADDR_ANY);
42   memset(&(local_addr.sin_zero),'\0',8);
43
44   if(bind(listen_fd,(struct sockaddr)&local_addr,sizeof(struct sockaddr))==-1) {
45     printf("unable to bind on port %d.\n",atoi(argv[1]);
46     exit(1);
47   }
48
49   if(listen(listen_fd,1)==-1) {
50     printf("error listening on port %d.\n",atoi(argv[1]));
51     exit(1);
52   }
53
54   if(send_fd=accept(listen_fd,(struct sockaddr *)remote_addr,
55   sizeof(struct sockaddr_in)) {
56     printf("accepting connection from %s port %d.\n",
57     inet_ntoa(remote_addr->sin_addr.s_addr),
58     ntohs(remote_addr->sin_port));
59
60       /* send stuff .... */
61       read_bytes=1;
62       while(read_bytes>0) {
63         char buf[1000];
64         read_bytes=read(stdin,(void *)buf,sizeof(buf));
65         send_bytes=send(send_fd,buf,sizeof(buf),0);
66       }
67
68       close(send_fd);
69       printf("connection closed ...\n");
70       prinrf("%d from %d total bytes sent.\n",send_bytes,read_bytes);
71       return 0;
72 }