Fortran

Guide To Learn

Creating a socket and listening for connections

We now have an IP address data structure, and we can initialize its value by calling the ipaddr_local function. Let’s now use this structure to open a socket and listen for incoming connections. To do this, we’ll use the tcp_listen function. Like before, we’ll first look at the interface of the C function from the libdill documentation:

int tcp_listen(
    const struct ipaddr* addr,
    int backlog);
  • addr–IP address to listen on
  • backlog–Maximum number of connections that can be kept open without accepting them

If successful, the return value is the newly created socket, represented by a single integer value. Otherwise, the return code is -1, indicating an error.

Simple enough! For our example, we’ll ignore the backlog–that is, we’ll just pass a zero to that argument–but we still need to implement it in the Fortran interface to the tcp_listen function:

integer(c_int) function tcp_listen(addr, backlog) &     ❶
               bind(c, name='dill_tcp_listen')          ❷
  import :: c_int, ipaddr                               ❸
  type(ipaddr), intent(in) :: addr                      ❹
  integer(c_int), value, intent(in) :: backlog          ❺
end function tcp_listen

❶ This function returns a c_int status.

❷ We’ll bind it to dill_tcp_listen.

❸ Imports the C-equivalent type kinds into the local scope

❹ The first argument (input) is an ipaddr struct.

❺ The second argument (input) is a c_int integer backlog.

As with previous interfaces, we’ll place this one inside the interface block in the mod_dill module. For simplicity, we won’t worry about the backlog argument and keeping connections without accepting them. To listen for incoming TCP connections, we’ll declare an integer(c_int) variable socket and add the following line after we initialize our IP address structure:

socket = tcp_listen(addr, 0_c_int)

This function call instructs the program to listen for incoming connections on a socket at the IP address and port number defined in the addr structure. Add this line to the program, recompile it, and run it. The output should be the same as at the end of the previous section. Now we’re ready for the fun stuff.

Creating a socket and listening for connections

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top