| 1 | # modbus_tcp_listen |
| 2 | |
| 3 | ## Name |
| 4 | |
| 5 | modbus_tcp_listen - create and listen a TCP Modbus socket (IPv4) |
| 6 | |
| 7 | ## Synopsis |
| 8 | |
| 9 | ```c |
| 10 | int modbus_tcp_listen(modbus_t *ctx, int nb_connection); |
| 11 | ``` |
| 12 | |
| 13 | ## Description |
| 14 | |
| 15 | The *modbus_tcp_listen()* function shall create a socket and listen to maximum |
| 16 | `nb_connection` incoming connections on the specified IP address. The context |
| 17 | `ctx` must be allocated and initialized with [modbus_new_tcp](modbus_new_tcp.md) before to |
| 18 | set the IP address to listen, if IP address is set to NULL or '0.0.0.0', any addresses will be |
| 19 | listen. |
| 20 | |
| 21 | ## Return value |
| 22 | |
| 23 | The function shall return a new socket if successful. Otherwise it shall return |
| 24 | -1 and set errno. |
| 25 | |
| 26 | ## Example |
| 27 | |
| 28 | For detailed examples, see source files in tests directory: |
| 29 | |
| 30 | - unit-test-server.c, simple but handle only one connection |
| 31 | - bandwidth-server-many-up.c, handles several connections at once |
| 32 | |
| 33 | ```c |
| 34 | ... |
| 35 | |
| 36 | /* To listen any addresses on port 502 */ |
| 37 | ctx = modbus_new_tcp(NULL, 502); |
| 38 | |
| 39 | /* Handle until 10 established connections */ |
| 40 | server_socket = modbus_tcp_listen(ctx, 10); |
| 41 | |
| 42 | /* Clear the reference set of socket */ |
| 43 | FD_ZERO(&refset); |
| 44 | |
| 45 | /* Add the server socket */ |
| 46 | FD_SET(server_socket, &refset); |
| 47 | |
| 48 | if (select(server_socket + 1, &refset, NULL, NULL, NULL) == -1) { |
| 49 | } |
| 50 | |
| 51 | ... |
| 52 | |
| 53 | close(server_socket); |
| 54 | modbus_free(ctx); |
| 55 | ``` |
| 56 | |
| 57 | ## See also |
| 58 | |
| 59 | - [modbus_new_tcp](modbus_new_tcp.md) |
| 60 | - [modbus_tcp_accept](modbus_tcp_accept.md) |
| 61 | - [modbus_tcp_pi_listen](modbus_tcp_pi_listen.md) |