Sending UDP packets at a specified rate

```Hello,

I am trying to understand how to write a simple network program that
sends UDP packets at a specified rate.

For example, let's say I want to send 500-byte packets at 40 Mbit/s

This means I want to send one packet every 0.1 ms

In my mind, the naive way to do that would be to write:

(pseudo code...)

while (1)
{
send(500-byte UDP packet);
sleep(0.1 ms);
}

But I don't think any of the sleep functions (nanosleep?) will let me
sleep for such a short period, will they?

Maybe I could send 10 packets, then sleep 1 ms? That might solve the
sleep problem, but my traffic would be very bursty.

I suppose I could waste time in a busy loop, but I don't like that solution.

Is there a (simple?) way to send 500-byte packets every 0.1 ms without
pegging the CPU to 100%?
```
 0
Spoon
4/18/2006 10:57:55 PM
comp.unix.programmer 10761 articles. 0 followers. kokososo56 (349) is leader.

11 Replies
1801 Views

Similar Articles

[PageSpeed] 28
```(Originally posted to comp.unix.programmer)

Spoon wrote:

> I am trying to understand how to write a simple network program that
> sends UDP packets at a specified rate.
>
> For example, let's say I want to send 500-byte packets at 40 Mbit/s
>
> This means I want to send one packet every 0.1 ms
>
> In my mind, the naive way to do that would be to write:
>
> (pseudo code...)
>
> while (1)
> {
>   send(500-byte UDP packet);
>   sleep(0.1 ms);
> }
>
> But I don't think any of the sleep functions (nanosleep?) will let me
> sleep for such a short period, will they?
>
> Maybe I could send 10 packets, then sleep 1 ms? That might solve the
> sleep problem, but my traffic would be very bursty.
>
> I suppose I could waste time in a busy loop, but I don't like that solution.
>
> Is there a (simple?) way to send 500-byte packets every 0.1 ms without
> pegging the CPU to 100%?
```
 0
Spoon
4/19/2006 12:30:11 PM
```Spoon wrote:
> Hello,
>
> I am trying to understand how to write a simple network program that
> sends UDP packets at a specified rate.
>
> For example, let's say I want to send 500-byte packets at 40 Mbit/s
>
> This means I want to send one packet every 0.1 ms
>
> In my mind, the naive way to do that would be to write:
>
> (pseudo code...)
>
> while (1)
> {
>   send(500-byte UDP packet);
>   sleep(0.1 ms);
> }
>
> But I don't think any of the sleep functions (nanosleep?) will let me
> sleep for such a short period, will they?

you could use usleep() but the timing won't be exactly right on a
non-real time os unless maybe you use a hardware timer and create an
interupt every X amount of time.

> Maybe I could send 10 packets, then sleep 1 ms? That might solve the
> sleep problem, but my traffic would be very bursty.

if that's an option it doesn't even matter if it's real time, use
usleep() that's what you are looking for.

> I suppose I could waste time in a busy loop, but I don't like that solution.

sure you could do that too.

> Is there a (simple?) way to send 500-byte packets every 0.1 ms without
> pegging the CPU to 100%?

using usleep().  cheers.

```
 0
purple_stars
4/19/2006 6:37:50 PM
```> you could use usleep() but the timing won't be exactly right on a
> non-real time os unless maybe you use a hardware timer and create an
> interupt every X amount of time.

and, just as with nanosleep(), not all systems that offer a usleep()
actually have that fine a granularity. To wit, from the usleep manpage
under HP-UX 11i:

Implementations may place limitations on the granularity of
timer values. For each interval timer, if the requested timer
value requires a finer granularity than the implementation
supports, the actual timer value will be rounded up to the next
supported value.

rick jones
--
oxymoron n, commuter in a gas-guzzling luxury SUV with an American flag
these opinions are mine, all mine; HP might not want them anyway... :)
feel free to post, OR email to rick.jones2 in hp.com but NOT BOTH...
```
 0
Rick
4/19/2006 9:44:41 PM
```purple_stars wrote:

> Spoon wrote:
>
>>I am trying to understand how to write a simple network program that
>>sends UDP packets at a specified rate.
>>
>>For example, let's say I want to send 500-byte packets at 40 Mbit/s
>>
>>This means I want to send one packet every 0.1 ms
>>
>>In my mind, the naive way to do that would be to write:
>>
>>(pseudo code...)
>>
>>while (1)
>>{
>>  send(500-byte UDP packet);
>>  sleep(0.1 ms);
>>}
>>
>> But I don't think any of the sleep functions (nanosleep?) will let me
>> sleep for such a short period, will they?
>
> you could use usleep() but the timing won't be exactly right on a
> non-real time os unless maybe you use a hardware timer and create an
> interupt every X amount of time.

The man page for usleep in Linux states:

This function is obsolete. Use nanosleep(2) or setitimer(2) instead.

>> Maybe I could send 10 packets, then sleep 1 ms? That might solve the
>> sleep problem, but my traffic would be very bursty.
>
> if that's an option it doesn't even matter if it's real time, use
> usleep() that's what you are looking for.

I'll give nanosleep() a try.

>> I suppose I could waste time in a busy loop, but I don't like that solution.
>
> sure you could do that too.

But I would hog the CPU even though I only need 2-3% of it on average...

Ugly.
```
 0
Spoon
4/20/2006 9:04:12 AM
```Spoon wrote:
> purple_stars wrote:
[snip]
> > if that's an option it doesn't even matter if it's real time, use
> > usleep() that's what you are looking for.
>
> I'll give nanosleep() a try.

i learned something too, i didn't know there was such a thing as
nanosleep() :)

```
 0
purple_stars
4/20/2006 2:59:21 PM
```The easy way to do it is just to keep track of the amount of bandwidth
you are using, and if it gets to high, sleep a bit before you send the
next bit.

If you are operating in contexts where you can't sleep, then just keep
a linked list of packets you need to send. Send them as appropriate.

For example, your send logic can go like this:

1) Is bandwidth usage high? If not, go to step 4.

2) Are there too many packets queued, if yes, return an error.

3) Queue the packet for later, return.

4) Is the bandwidth usage low and there are packets queued? If so, send
some of them and update the bandwidth estimate.

5) If we emptied the queue, send this packet (updating the bandwidth
estimate) and return. If not, queue this packet and return.

DS

```
 0
davids
4/20/2006 4:25:01 PM
```You may find that the nanosleep function uses a 10 ms. precision, such
that the smallest delay such as 1 ms. takes at least 10 ms.

You can work around this limitation by tracking the actual sleep time
and feeding any excess sleep time into the next delay calculation.
Gettimeofday returns very accurate time information.  This is how I
solved this very problem.

Bill Lindquist

```
 0
William
4/24/2006 3:04:28 PM
```William.Lindquist@lmco.com wrote:
> You may find that the nanosleep function uses a 10 ms. precision,
> such that the smallest delay such as 1 ms. takes at least 10 ms.

> You can work around this limitation by tracking the actual sleep
> time and feeding any excess sleep time into the next delay
> calculation.

Don't you still end-up with bursts as the excess sleep time becomes no
sleeps for a while?

> Gettimeofday returns very accurate time information.  This is how I
> solved this very problem.

Careful there - I have seen - in the past anyway - gettimeofday only
increment by "large" chunks on some platforms - old Irix comes to mind
- I think it was an issue for SPECweb96 benchmarking.  And just about
any "gettimeofday" replacement under Windows may only increment in 10
ms chunks. (eg glib g_get_current_time() and its use of
GetSystemTimeAsFileTime())

When one doesn't need actual wall-clock time, going with something a
bit more platform-specific - at least for measuring "time" may be
useful/accurate/precise.  gethrtime() on those platforms which have
it, or something along those lines.  It doesn't solve the problem of
getting short sleep times, but it will tend to allow much finer
granularity of "time" measurement.

rick jones

I'm always confusing accuracy and precision

If one has a multiple CPU system, or even multiple systems on the
network, one could I suppose "sacrifice" one CPU to sit and spin
watching time pass and "chime" to affect the short timeouts by sending
messages to the other processes which wanted to have short timeouts
but not sit and spin.  Probably still burn a lot of cycles, but
perhaps not as many as having everyone spinning

--
No need to believe in either side, or any side. There is no cause.
There's only yourself. The belief is in your own precision.  - Jobert
these opinions are mine, all mine; HP might not want them anyway... :)
feel free to post, OR email to rick.jones2 in hp.com but NOT BOTH...
```
 0
Rick
4/24/2006 5:28:55 PM
```Gettimeofday is much more accurate then usleep (using IRIX 6.5.4 and
LINUX).  And there is no guarantee that the process will be immediately
restarted if other processes are competing.

Since usleep never returned to me in less than 10 ms. I adjusted the
delay time on the next iteration to compensate.  This causes some
acceptable burstiness.  So I might ask for a 5 ms. delay, get 10 ms.
and skip the delay the next iteration.  Overall the throughput gets me
what I want.

Otherwise, I would usleep for 5 ms. and delay 10 ms. each iteration
halving my throughput.

```
 0
William
4/25/2006 11:53:27 PM
```or you could use the "select" system call with all fields empty except
for the timeout. timeout is of struct timeval* type, so you could put
there as many/few usec you want.

```
 0
doina
4/26/2006 8:51:14 AM
```doina babu wrote:
> or you could use the "select" system call with all fields empty except
> for the timeout. timeout is of struct timeval* type, so you could put
> there as many/few usec you want.
>
The minimum timeout for select is still limited by the system tick.

--
Ian Collins.
```
 0
Ian
4/26/2006 9:11:58 AM
 Reply:
Similar artilces about - Sending UDP packets at a specified rate:

Send a SNMP Trap
hy, I'm using wengsoft snmp implementation to send a snmp trap. But the information sent by the trap isn't as I would expect. My code: static void sendTrap(String contextID, String contextName) throws java.io.IOException { // Create SNMP message object, it may contain one of the following // protocol data unit : GET, SET, TRAP, GET-NEXT. snmpMessage = new SnmpMessage(); // create a Set Protocol Data Unit. trapPdu = new SnmpGetSetPdu(); trapPdu.setMsgType(AsnObject.SNMPV2_TRAP); trapPdu.setReqId(1); snmpMessage.setPdu(trapPdu); snmpMessage.setSnmpVersion(3); ...

Sending out a probe
TCP-IP question: From the manual: " TCP keep alive (TCPKEEPALV) - Help Specifies the amount of time, in minutes, that TCP waits before sending out a probe to the other side of a connection. The probe is sent when the connection is otherwise idle, even when there is no data to be sent. " Because we have frequent disconnects on the Telnet sessions we have had a sniffer running on one of the PC's on which we expected the probe to come in. But we have never seen some kind of bit coming in from the AS400. Do we do something wrong or should we open some po...

send mail in FMP with Exchange Server ?
Hi, For the Send Mail script in FileMaker vers. 9.0 , it works perfectly if my syst�me is win XP with the Outlook Express installed. And when I put this DB in a winXP with an account of Exchange Server, the Send Mail script doesn't work ! Is this normal or do I have to do something ? Thanks for your help Hi Eric, in FM 7 the problem is that there must be the email program be mentioned in the options of Internet Explorer (in our case). So we are working with Lotus Notes and by default the corresponding email program is outlook express. So open e.g. Internet Explorer then Tools /...

Transaction rate question
Hello Before auditing a database I need to know the transaction rate, how I can compute it from the dictionary ? Thank you "Sylvestre" <Sylvestre@world.com> wrote in message news:43b995a6\$0\$290\$636a55ce@news.free.fr... > Hello > > Before auditing a database I need to know the transaction rate, how I can > compute it > from the dictionary ? > > Thank you > You can use Statspack to calculate this. Take a Statspack snapshot at 2 different time periods and generate a report which will show you the number of transactions between the 2 periods. M...

Problems with send /delete command
I have Kermit running on Linux Release 9 and have the following lines in my script (This first logs me onto a remote server running Linux 7.3 and has Kermit): set host /pty ssh -e none l root xxx.xxx.xx.xxx if fail stop 1 minput 30 "password:" ">" if < \v(minput) 1 stop 1 "MINPUT = \v(minput)" switch \v(minput) { :1, echo PASSWORD INPUT OK lineout xxxxxxxxxx input 30 "#" if fail stop 1 PROMPT INPUT FAILED :2, echo PROMPT INPUT OK lineout "kermit -x" input 20 "KERMIT READY TO SERVE..." rcd...

Send mail
I want to send an email with attachment using mpack.(UNIX/LINUX/AIX). Is there a startup param like "mailx -r" where you can change the senders address? ...

sending eMail Attachment
Hy, does anybody know a simple, easy to use package to send a binary file as an eMail attachemt over the local unix/linux sendmail service. I want to write a procedure like: proc sendFileViaEmail {to subject text fileList} { # build whats neccessey in file ..... write_file file \$emailbody #send exec cat file | sendmail -t } tx TAB Tillmann Basien wrote: > Hy, > does anybody know a simple, easy to use package to send a binary file as an > eMail attachemt over the local unix/linux sendmail service. > I want to write a procedure like: > > proc sendFil...

UDP Socket problem
Hi there, I try to write a comm program based on udp broadcasting protocol. I did the following: SERVER: require 'socket' server = UDPSocket.open server.bind('0.0.0.0', 4321) while true do p server.recvfrom(10) end CLIENT require 'socket' socket = UDPSocket.open socket.setsockopt(Socket::SOL_SOCKET, Socket::SO_BROADCAST, true) socket.send("sample", 0, '255.255.255.255', 4321) Now there are 2 problems: 1) the server will print out 2 line of data e.g.: ["sample", ["AF_INET", 1339, "XRFANG-OTM", "192.168.1.101&...

Sending errors from psql to error file
Hello, I am trying to migrate a client from one database to another. Basically we designed a web application for them using Postgresql but we have made many changes to the design of our application since version 1. Now they want to upgrade. So basically I have to pg_dump their current data and then import it into our new schema. Now, of course I realize that there are going to be errors. But they have a lot and I mean a lot of data. I don't want to have to sit there and watch the import go by, I want to run a command and then look in a file for any errors after the import i...

Problem sending faxes through VoIP
Hello every one! I have a problem sending faxes through VoIP This is what we have: PBX with VoIP Card --- Cisco --- E1 --- (Internet VPN) --- T1--- Cisco --- PBX The cisco router has activate the QoS, to priority the communication saving 512 kbps of bandwidth, for the matching VoIP ports. The voice and faxes work fine, but when the bandwidth is over use, the voice is not affected but the faxes can not communicate even when the QoS is saving bandwidth for them. I been trying with traffic-shape, fax passthrough , fax relay and other options, but no one fix the problem. I figure out that t...

how to send pick up the email address from a field in a .dbf & send emails thru outlook express....
hello all: i have a client.dbf with a field: CLIENTEMAIL when my main.exe prints reminder letters, i want my main.exe to open outlook express & pick up the email address from field:CLIENTEMAIL & ALSO attach the outstanding bills .pdf file (which would be already saved using pscript32) the email body should pick up the text saved in fields: remtxt1,remtxt2,remtxt3... (i.e: the reminder letter message) regards Hi I sugest to use hb_sendmail function to send the emails Regards Luiz Em sexta-feira, 20 de fevereiro de 2015 06:21:08 UTC-2, timec...@gmail.com escreveu:...

Instability of Linux crapware sends user scrambling back to Windows
"Ubuntu for me was meant to provide a more stable platform than Windows. Since this freezing has begun, it's been anything but that. In fact, it's made Windows look rock solid! Sadly, I'm switching back to Windows until this gets sorted. I'm fed up with spending hours trawling the web to find solutions to a problem which seems to be affecting so many people, but to which no permanent fix looks like being released for now." #143 at http://ubuntuforums.org/showthread.php?t=412125&page=15 ...

how to send SCSI Command?
I'm developing a iSCSI Target Project. I have finished the iSCSI Protocol Parse in UserMode as a Windows Service. in this project, we should provide a filedisk or a partition to client read/write data. now I should send the SCSI command to a volume at target host, in oder to write/read the data. but how to send SCSI comand to lower device.which device that I should send SCSI Command to ? thanks a lot of any suggestion or giving any reference=A1=A3 >but how to send SCSI comand to lower device.which IOCTL_SCSI_PASS_THROUGH_DIRECT -- Maxim Shatskih, Windows DDK MVP S...

send
I set up a wireless network using a linksys 54g router, I have 5 desktops computer, and several Laptops being used at various times . I have assigned IP address to the desktop and the laptop obtain addresses automatically. All desktops are using XP, My problem have been in setting up a network workgroup, I have used the wizard , but still I can not share files. When I click on view network I see the workgroups, but when I click onto My network place I can not open files that have been shared. Also can any one tell me how to delete a network workgroup that has been setup. Thanks ...

Format Specifier
Hello, &nbsp; I record the data of my experiment using Write to Spreadsheetfile. In past experiments, I made a mistake in the format specifier i.e. I wrote: %3.6f (which means width = 3 and 6 digits of precision which is wrong). I should have written %6.3f. But when I open the recorded Spreadsheetfile with Notepad (for instance), It seems that Labview recorded the data correctly. &nbsp; Can I trust these data ? If yes, why ? &nbsp; When I use Read&nbsp;from Spreadsheetfile using the wrong format specifier given above, it doesn't work which is understandable because I use t...

send-hooks
Hi, I have a problem using send-hooks. I would like to use it this way: ---cut--- send-hook . unmy_hdr send-hook 'gentoo-user-de@gentoo.org' 'my_hdr Reply-To: \ gentoo-user-de@gentoo.org' ---cut--- to make it a little harder for people to CC me.[1] However, when I am in the ML-box, have send a mail using list-reply to this ML and would like to send a PM reply to a person later, the Reply-To header is still set to the ML. As the To: is not to the list in this cases I hoped the default unmy_hdr should work, like it works when the first mail is a PM. Any h...

Sending Files
Hi Everyone, I have a client/server program that communicate using both TCP and Multicast. My broadcast messages go through Multicast, and client specific messages goes through the TCP socket. Anyway, during all these operations I will have to send some files from the server to the client, about 11 files that are all together 500K. I am wondering if I could use an FTP protocol to send the files from one program to the other. The reason that I am asking is that I am trying to find a way so that I don't have to worry about checksums and all that stuff. I appreciate any sugges...

mail() function sending two emails
Here's my code: \$today = getdate(); \$to = someone@somewhere.com; \$subject = "New Application: ".\$userdata["username"]." - ".\$today['mon']."/".\$today['mday']."/".\$today['year']; \$message_header = "New Application: ".\$userdata["username"]; \$message = \$message_header."\n Hello, is this working?"; mail(\$to, \$subject, \$message); It's not located in a loop, so I don't understand why it would send 2 emails to the reciever? Any idea's? Jesse Burns aka jburns131 wrote:...

Getting packet loss stats from /proc?
Hi, is it posible to get some stats/numbers about tcp/udp packet loss via /proc? Many thanks Oliver Oliver Schulze L. wrote: > Hi, > is it posible to get some stats/numbers about tcp/udp packet loss via /proc? > > Many thanks > Oliver You can find total packet errors, drops and collisions in /proc/net/dev. In addition /proc/net/tcp and /proc/net/udp will show some stats on retransmits. You can derive loss from there. -- Mike Nugent Programmer/Author/DBA/Admin In search of employment, email for credentials news@remove-this.illuminatus.org ...

Sending message to users inside an application
Hi all, I have an application written in Powerbuilder 8.0 and i'd like to add a way to administrators send a message to users currently inside the application (like "The Server needs to restart... etc... " ), anyone have any ideas? Many Thanks kingsnake@netcabo.pt You didn't say what database software you're using. For instance, in Oracle, you could set it up so that either your MDI frame or a hidden window has an event that uses a timer to listen for a specific alert and display a pop-up or a messagebox with the alert contents when it receives one. ...

Re: USTA Sends Strange Letter to Wal-Mart #5
>> Completely agreed. If VoIP is so great, it should be able to support >> the same obligations as real telephony such as 911 and USF. > Should email have similar "obligations"? Of course not. It doesn't purport to be telphony, and it doesn't interoperate with the other billion phones on the face of the planet. > So long as I know what I'm getting, I am perfectly happy paying > for my "fake telephony". > And, VoIP or no, the USF should be elimated. Now. Immediately. > Yesterday, if possible. I think you might enj...

RedHat ES 3.0 send mail does sendmail need to be on
Does sendmail need to be on to send mail? LHradowy wrote: > Does sendmail need to be on to send mail? Most mail clients don't have a built in SMTP, so you need to configure the mailcleinet to use one and it don't have to be a local one. On Thu, 01 Apr 2004 12:41:05 -0600, LHradowy wrote: > Does sendmail need to be on to send mail? No. If your ISP gives you server names such as smtp.your-isp.com for outgoing and pop.your-isp.com for incoming, just use those addresses in your mail client and they will go via your ISP. Regards, Dave On Thu, 01 Apr 2004 12:41:05 -0600 LHr...

High rate data transfer from off-chip mem to FSL co-proc...
Hi guys, Sorry this subject was discussed in a different way a year ago. However: I have a Microblaze based system and I need to attach some co-processors to it to implement several applications. The problem is that I can't put all my data on the BRAMs so I have to use off-chip memory in my design. I know that I can have DMA on OPB bus (I think from off-chip mem controller to OPB BRAMs, yes?) however for contention reasons and low communication bandwidth as well as high power consumption I'd really rather not put the co-processors on the OPB bus however on the other hand I don't w...

l2tp udp checksums in 12.4T
Ok, this is a weird one. I noticed that a vpdn configuration that I have used since 12.2 was not doing what I expected in 12.4(15)T. In particular, udp checksums were not on even though the vpdn group specified "l2tp ip udp checksum". As far as I can tell, this configuration command is now completely ignored in the vpdn group itself although it does work if applied to the unnamed vpdn template. This is true even if the vpdn group specifies "no source vpdn-template". Were it not for the latter I would think they just got the sense of "default" reversed but cl...

High baud rate chips for RS232 protocol
Hello all, I am interested in designing a custom board with serial interface and I am searching for RS232 port driver ICs which can support baud rates higher than 230kbps. There are many PCI or USB to serial interface options available which support bauds of upto 920kbps. I have designed a UART interface in FPGA but need higher baud rate driver ics to actaully get the performance I require. Any recommendations? Thanks On 3 Sep 2005 13:05:40 -0700, "Mak" <mansoor.naseer@gmail.com> put finger to keyboard and composed: >I am interested in designing a cu...