问题
Possible Duplicate:
How do you throttle the bandwidth of a socket connection in C?
I'm writing a simple FTP server in C for a Unix environment. As a feature of the server, I want to limit the upload/download speed of a user.
Are there any library functions directly solve this problem?
If not, what's the algorithm used in a production FTP server? I have a very naive solution: calculate how many bytes to send in a second, say
x
,write(x)
orread(x)
, and thensleep(1)
.
There should be a better solution. Even better if there are code samples.
To be clear, I'm using Mac OS X, but I wish it could also run under Ubuntu or some Linux.
回答1:
FTP is a application layer protocol . FTP can run on TCP or UDP sockets. (EDIT: tftp and uftp runs on udp, pls see the comment section for details)
The Socket Speed is a function of following :
- link Speed :10/100 Base T and so on.
- BER of the link : Bit Error rate (typically in today's world its generally low 10 to the power -9 or something of that sort . there are burst errors as well.
- Socket Buffer sizes :
/proc/sys/net/core
parameters
On linux : For handling the TCP Sockets here's a good article [1]
4.Tweak the stack to filter/drop packets to introduce the packet loss , thus eventually throttling the flow rate : Tools like netem[2] help you adjust the buckets to throttle the flows.
[1] http://www.cyberciti.biz/faq/linux-tcp-tuning/
[2] http://www.linuxfoundation.org/collaborate/workgroups/networking/netem
回答2:
Are you sure you want to do this? Is your motive to annoy your users? (this is a legitimate motive - see any of the several "free upload" sites)
Bandwidth limiting like this is not a good way to protect your server from overload. people will find threaded clients and open concurrent FTP sessions...
are there any library functions to do that?
Probably not, bandwidth shaping is an OS task not a service task.
what's the algorithm?
The one you describe sounds fairly effective.
To make it better could look at how many octets have been read or written and how much time has been spent before deciding to sleep. Consider the case where the client is slower than your limit: the reads and writes will end up blocking and your sleep() will just add unneccessary latency. this will also reduce hide effects of disk latency etc from the user.
You could consider using usleep or nanosleep for finer resolution both are in posix so should be on OSX *BSD and linux.
来源:https://stackoverflow.com/questions/10628472/how-do-i-limit-socket-speed-in-c