1 /* stream.c - streaming server
13 /* socket and bind stuff */
14 #include <sys/types.h>
15 #include <sys/socket.h>
18 #include <netinet/in.h>
21 #include <arpa/inet.h>
34 #define PRINT_RATE 100
36 int print_rate(struct timeval *time_start,int t) {
43 gettimeofday(&now,NULL);
44 sec_t=now.tv_sec-time_start->tv_sec;
45 usec_t=(now.tv_usec<time_start->tv_usec)
46 ?1000000-time_start->tv_usec+now.tv_usec
47 :now.tv_usec-time_start->tv_usec;
48 delta_t=sec_t*1000000+usec_t;
49 kbs_t=(t/delta_t)*(1000000/1024);
50 count=printf("total: %d MByte - average: %d kB/s",t/(1024*1024),kbs_t);
51 while(count--) printf("\b");
56 int main(int argc, char *argv[]) {
57 int listen_fd, send_fd;
58 struct sockaddr_in local_addr, remote_addr;
59 socklen_t remote_addr_len;
60 int send_bytes, read_bytes, total_read=0, total_send=0;
61 struct timeval time_start;
65 printf("usage: %s <port>\n",argv[0]);
69 if((listen_fd=socket(AF_INET,SOCK_STREAM,0)) == -1) {
70 printf("can't open socket.\n");
74 memset(&local_addr,0,sizeof(local_addr));
75 local_addr.sin_family=AF_INET;
76 local_addr.sin_port=htons(atoi(argv[1]));
77 local_addr.sin_addr.s_addr=htonl(INADDR_ANY);
79 if(bind(listen_fd,(struct sockaddr *)&local_addr,sizeof(local_addr))==-1) {
80 printf("unable to bind on port %d.\n",atoi(argv[1]));
85 if(listen(listen_fd,1)==-1) {
86 printf("error listening on port %d.\n",atoi(argv[1]));
90 remote_addr_len=sizeof(remote_addr);
91 if((send_fd=accept(listen_fd,(struct sockaddr *)&remote_addr,
92 &remote_addr_len))!=-1) {
93 printf("accepting connection from %s port %d.\n",
94 inet_ntoa(remote_addr.sin_addr),
95 ntohs(remote_addr.sin_port));
98 gettimeofday(&time_start,NULL);
100 /* send stuff .... */
102 while(read_bytes>0) {
103 unsigned char buf[MAX_SIZE];
105 read_bytes=read(0,buf,sizeof(buf));
106 total_read+=read_bytes;
107 send_bytes=send(send_fd,buf,read_bytes,0);
108 total_send+=send_bytes;
109 if(!((i++)%PRINT_RATE)) print_rate(&time_start,total_send);
114 printf("connection closed ...\n");
115 printf("%d from %d total bytes sent.\n",total_send,total_read);