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