RateLimitedSocket.cc

Go to the documentation of this file.
00001 /*
00002  *    Copyright 2006 Intel Corporation
00003  * 
00004  *    Licensed under the Apache License, Version 2.0 (the "License");
00005  *    you may not use this file except in compliance with the License.
00006  *    You may obtain a copy of the License at
00007  * 
00008  *        http://www.apache.org/licenses/LICENSE-2.0
00009  * 
00010  *    Unless required by applicable law or agreed to in writing, software
00011  *    distributed under the License is distributed on an "AS IS" BASIS,
00012  *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
00013  *    See the License for the specific language governing permissions and
00014  *    limitations under the License.
00015  */
00016 
00017 
00018 #include "RateLimitedSocket.h"
00019 
00020 namespace oasys {
00021 
00022 //----------------------------------------------------------------------
00023 RateLimitedSocket::RateLimitedSocket(const char* logpath,
00024                                      u_int32_t rate,
00025                                      IPSocket* socket)
00026     : Logger("RateLimitedSocket", logpath),
00027       bucket_(logpath, rate, 65535 * 8 /* max udp packet */),
00028       socket_(socket)
00029 {
00030 }
00031 
00032 //----------------------------------------------------------------------
00033 int
00034 RateLimitedSocket::send(const char* bp, size_t len, int flags)
00035 {
00036     ASSERT(socket_ != NULL);
00037 
00038     if (bucket_.rate() != 0) {
00039         bool can_send = bucket_.drain(len * 8);
00040         if (!can_send) {
00041             log_debug("can't send %zu byte packet since only %u tokens in bucket",
00042                       len, bucket_.tokens());
00043             return IORATELIMIT;
00044         }
00045 
00046         log_debug("%u tokens sufficient for %zu byte packet",
00047                   bucket_.tokens(), len);
00048     }
00049 
00050     return socket_->send(bp, len, flags);
00051 }
00052 
00053 //----------------------------------------------------------------------
00054 int
00055 RateLimitedSocket::sendto(char* bp, size_t len, int flags,
00056                           in_addr_t addr, u_int16_t port)
00057 {
00058     ASSERT(socket_ != NULL);
00059 
00060     if (bucket_.rate() != 0) {
00061         bool can_send = bucket_.drain(len * 8);
00062         if (!can_send) {
00063             log_debug("can't send %zu byte packet since only %u tokens in bucket",
00064                       len, bucket_.tokens());
00065             return IORATELIMIT;
00066         }
00067 
00068         log_debug("%u tokens sufficient for %zu byte packet",
00069                   bucket_.tokens(), len);
00070     }
00071 
00072     return socket_->sendto(bp, len, flags, addr, port);
00073 }
00074 
00075 } // namespace oasys

Generated on Sat Sep 8 08:43:32 2007 for DTN Reference Implementation by  doxygen 1.5.3