Penetration into the Internet of Things network is a challenge in the security of new-generation networks and smart cities. In most cases, malware is distributed in the Internet of Things and smart objects are infected by malware. Objects infected with malware or viruses, which are called botnets, perform attacks such as DDoS against network services. DDoS attacks make network services inaccessible to users. A suitable approach to detect attacks based on malware and botnet is to use intelligent and distributed intrusion detection systems in the Internet of Things and smart cities. In other research, a centralized architecture and deep learning and machine learning method have been used to design intrusion detection systems. Centralized approaches have limited ability to process large volumes of traffic and are vulnerable to DDoS attacks. In this paper, a distributed intrusion detection system is designed with two stages dimensionality reduction and classification. In the first stage, a new and improved version of the whale optimization algorithm(WOA) has been used to select features and reduce traffic dimensions in fog nodes. In the second stage, each fog node performs the classification of the important features of the network traffic by voting and combined learning. The fog nodes share the IP address of the attacking nodes with the detection of the attacking node. Experiments showed that the improved WOA algorithm has less error in calculating the optimal solution than the optimization algorithm of the WOA algorithm. Reducing the feature selection objective function in the proposed method shows that the WOA algorithm is finding optimal features for intrusion detection and reducing the intrusion detection error. The advantage of the proposed intrusion detection system is to deal with DDoS attacks and cooperation between fog nodes to share blacklists. Tests showed that the proposed method in detecting network intrusion without feature selection has accuracy, sensitivity, and precision of 98.21%, 98.09%, and 97.88%. The proposed method with feature selection has accuracy, sensitivity, and precision of 99.39%, 99.31%, and 99.28%. The accuracy and precision of the proposed method in network intrusion detection are higher than the gray wolf algorithm, genetics and support vector machine, the binary gray wolf algorithm, and the hybridized GWO and GA algorithm. The proposed method is more accurate in intrusion detection than the GWO + PSO and firefly algorithms.