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