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");
57 int main(int argc, char *argv[]) {
58 int listen_fd, send_fd;
59 struct sockaddr_in local_addr, remote_addr;
60 socklen_t remote_addr_len;
61 int send_bytes, read_bytes, total_read=0, total_send=0;
62 struct timeval time_start;
66 printf("usage: %s <port>\n",argv[0]);
70 if((listen_fd=socket(AF_INET,SOCK_STREAM,0)) == -1) {
71 printf("can't open socket.\n");
75 memset(&local_addr,0,sizeof(local_addr));
76 local_addr.sin_family=AF_INET;
77 local_addr.sin_port=htons(atoi(argv[1]));
78 local_addr.sin_addr.s_addr=htonl(INADDR_ANY);
80 if(bind(listen_fd,(struct sockaddr *)&local_addr,sizeof(local_addr))==-1) {
81 printf("unable to bind on port %d.\n",atoi(argv[1]));
86 if(listen(listen_fd,1)==-1) {
87 printf("error listening on port %d.\n",atoi(argv[1]));
91 remote_addr_len=sizeof(remote_addr);
92 if((send_fd=accept(listen_fd,(struct sockaddr *)&remote_addr,
93 &remote_addr_len))!=-1) {
94 printf("accepting connection from %s port %d.\n",
95 inet_ntoa(remote_addr.sin_addr),
96 ntohs(remote_addr.sin_port));
99 gettimeofday(&time_start,NULL);
101 /* send stuff .... */
103 while(read_bytes>0) {
104 unsigned char buf[MAX_SIZE];
106 read_bytes=read(0,buf,sizeof(buf));
107 total_read+=read_bytes;
108 send_bytes=send(send_fd,buf,read_bytes,0);
109 total_send+=send_bytes;
110 if(!((i++)%PRINT_RATE)) print_rate(&time_start,total_send);
115 printf("connection closed ...\n");
116 printf("%d from %d total bytes sent.\n",total_send,total_read);