C and C++ Binaries


IO.SOCK.STATE : Socket In Wrong State

Summary

A socket operation is performed on a socket that is not in the correct state for that operation.

Properties

Class Name Socket In Wrong State
Significance reliability
Mnemonic IO.SOCK.STATE
Categories
MisraC2023 MisraC2023:D.4.13 Functions which are designed to provide operations on a resource should be called in an appropriate sequence
Misra2012 Misra2012:D.4.13 Functions which are designed to provide operations on a resource should be called in an appropriate sequence
CWE CWE:666 Operation on Resource in Wrong Phase of Lifetime
  CWE:696 Incorrect Behavior Order
Availability Available for C and C++.
Enabling Checks for this warning class are disabled by default. To enable them, add the following WARNING_FILTER rule to the project configuration file.
WARNING_FILTER += allow class="Socket In Wrong State"

Example

#include <sys/socket.h>
#include <unistd.h>

int listen_no_bind(){
    int sock = socket(PF_LOCAL, SOCK_STREAM, 0);
    struct sockaddr a;
    socklen_t alen = sizeof(struct sockaddr);
    int res;

    if (sock < 0 ) return -1;
    res = listen(sock, SOMAXCONN); /* 'Socket In Wrong State' warning issued here
                                    * - socket has not been bound
                                    */
    close(sock);
    return res;
}


int listen_after_bind(){
    int sock = socket(PF_LOCAL, SOCK_STREAM, 0);
    struct sockaddr a;
    socklen_t alen = sizeof(struct sockaddr);
    int res;

    if (sock < 0 ) return -1;
    res = bind(sock, &a, alen);
    if (res >= 0){
      res = listen(sock, SOMAXCONN);               /* ok: socket has been bound with bind() */
    }
    close(sock);
    return res;
}

Triggering Functions

Triggering Functions Triggered When
int accept(int s, struct sockaddr *addr, socklen_t *addrlen) Socket s is not being listened to via a call to listen().
int bind(int sockfd, void *my_addr, int addrlen); Socket sockfd has not been initialized with a call to socket().
int connect(int sockfd, const struct sockaddr *serv_addr, socklen_t addrlen) Socket sockfd is already being listened to (via a call to listen()).
int listen(int sockfd, int backlog); Socket sockfd has not been bound with bind().
int recv(int sockfd, void *buf, size_t len, int flags) Socket sockfd has not been connected with connect().
int send(int s, const void *msg, size_t len, int flags) Socket s has not been connected with connect().

Relevant Configuration File Parameters

The following configuration file parameters affect checks for this warning class.