The internet of things (IoT) is exposed to various cyber attacks that target its security. An intrusion detection system (IDS) in the IoT must be able to detect attacks and their types and identify complex and new attacks. The IDS in the IOT must have a distributed architecture to process large network traffic. Training machine learning methods and learning key features increases the accuracy of the IDS. This manuscript proposes a distributed IDS deployed within the fog layer. The initial step involves leveraging game theory and Generative Adversarial Networks (GANs) and traffic balancing. Subsequently, enhanced with opposition-based learning, the Jellyfish Search (JS) optimizer algorithm facilitates feature selection within fog nodes. Utilizing majority voting and weighting mechanisms, fog nodes determine optimal feature vectors. To prevent manipulation, feature vectors are exchanged via blockchain. Each fog node employs three classifiers-Multi-Layer Perceptron (MLP), Random Forest (RF), and XGBoost-utilizing ensemble learning techniques. Fog nodes maintain blacklists, updating them via blockchain. The Embedded Learning + IJSO (EJSO) framework offers benefits such as network traffic balancing, intelligent dimension reduction, embedded learning, and privacy preservation through blockchain integration. Experimental evaluation conducted on NSL-KDD and UNSW-NB15 datasets demonstrates the efficacy of the EJSO method in attack detection. The introduced clustering method, incorporating fuzzy clustering and the Arithmetic Optimization Algorithm (AOA), showcases high accuracy, sensitivity, and precision rates. Specifically, in the NSL-KDD dataset, the EJSO method achieves accuracy, sensitivity, and precision rates of 99.87, 99.66, and 99.12%, respectively. In the UNSW-NB15 dataset, these rates stand at 98.82, 98.74, and 98.59%, respectively. Additionally, the EJSO method outperforms existing techniques regarding dimension reduction and attack detection accuracy, surpassing methods such as LSTM, GA + SVM, transfer learning, and neural networks.