The realization of the Internet of Things (IoT) paradigm relies on the implementation of systems of cooperative intelligent objects with key interoperability capabilities. In order for objects to dynamically cooperate to IoT applications' execution, they need to make their resources available in a flexible way. However, available resources such as electrical energy, memory, processing, and object capability to perform a given task, are often limited. Therefore, resource allocation that ensures the fulfilment of network requirements is a critical challenge. In this paper, we propose a distributed optimization protocol based on consensus algorithm, to solve the problem of resource allocation and management in IoT heterogeneous networks. The proposed protocol is robust against links or nodes failures, so it's adaptive in dynamic scenarios where the network topology changes in runtime. We consider an IoT scenario where nodes involved in the same IoT task need to adjust their task frequency and buffer occupancy. We demonstrate that, using the proposed protocol, the network converges to a solution where resources are homogeneously allocated among nodes. Performance evaluation of experiments in simulation mode and in real scenarios show that the algorithm converges with a percentage error of about±5% with respect to the optimal allocation obtainable with a centralized approach