This paper investigates the control of flow networks, where the control objective is to regulate the measured output (e.g storage levels) towards a desired value. We present a distributed controller that dynamically adjusts the inputs and flows, to achieve output regulation in the presence of unknown disturbances, while satisfying given input and flow constraints. Optimal coordination among the inputs, minimizing a suitable cost function, is achieved by exchanging information over a communication network. Exploiting an incremental passivity property, the desired steady state is proven to be globally asymptotically attractive under the closed loop dynamics. Two case studies (a district heating system and a multi-terminal HVDC network) show the effectiveness of the proposed solution.