19

I read the man 2 listen.

I don't understand what is the backlog value, it says

The backlog argument defines the maximum length to which the queue of pending connections for sockfd may grow

Right, how can I define what is the best value?

Thanks

mathieug
  • 901
  • 1
  • 11
  • 24
  • 1
    possible duplicate of [socket listen backlog parameter, how to determine this value?](http://stackoverflow.com/questions/114874/socket-listen-backlog-parameter-how-to-determine-this-value) – caf Apr 04 '12 at 03:25

2 Answers2

18

Basically, what the listen() backlog affects is how many incoming connections can queue up if your application isn't accept()ing connections as soon as they come in. It's not particularly important to most applications. The maximum value used by most systems is 128, and passing that is generally safe.

  • Okay, if I `listen(sockfd, 5)`, should I test in my `accept()` (in my infinite loop) if `current_nb_client < 5` in order to send a error message to my client or can I trust backlog and handle this in client-side? – mathieug Apr 03 '12 at 23:57
  • 2
    No, that's not necessary -- as long as you're accepting connections as soon as they come in, the length of your listen backlog is irrelevant. You can have as many *active* connections as you need; the listen backlog only affects connections which haven't been fully established. –  Apr 04 '12 at 00:26
  • Oh, I've just understand! I thought they do not disappear from the queue. But no! It's a pending queue, and I just have to `accept()` each and they disappear from the queue. – mathieug Apr 04 '12 at 01:04
4

It's a fight between clients trying to connect. pushing accept requests onto the queue, and the accept thread/s sucking them off. Usually, the threads win. I usually set at 32, but it's not usually an important parameter.

Martin James
  • 24,453
  • 3
  • 36
  • 60
  • Okay, if I `listen(sockfd, 5)`, should I test in my `accept()` (in my infinite loop) if `current_nb_client < 5` in order to send a error message to my client or can I trust backlog and handle this in client-side? – mathieug Apr 03 '12 at 23:57
  • 1
    The connection attempt will be refused if the queue is full, but it's just so unlikely to happen that you should forget about it. There has to be a bit of a queue to cover those times when it just happens that a lot of connection rquests come in in a burst but, overall, todays processors/memory/OS/whatever are easily able to keep up with busy networks. – Martin James Apr 04 '12 at 07:38