How Do Sockets Work in C?

前端 未结 4 929
渐次进展
渐次进展 2021-02-04 02:02

I am a bit confused about socket programming in C.

You create a socket, bind it to an interface and an IP address and get it to listen. I found a couple of web resources

4条回答
  •  终归单人心
    2021-02-04 02:34

    Short answer is that you have to do all the heavy lifting yourself. You can be notified that there is data available to be read, but you won't know how many bytes are available. In most IP protocols that use variable length packets, there will be a header with a known fixed length prepended to the packet. This header will contain the length of the packet. You read the header, get the length of the packet, then read the packet. You repeat this pattern (read header, then read packet) until communication is complete.

    When reading data from a socket, you request a certain number of bytes. The read call may block until the requested number of bytes are read, but it can return fewer bytes than what was requested. When this happens, you simply retry the read, requesting the remaining bytes.

    Here's a typical C function for reading a set number of bytes from a socket:

    /* buffer points to memory block that is bigger than the number of bytes to be read */
    /* socket is open socket that is connected to a sender */
    /* bytesToRead is the number of bytes expected from the sender */
    /* bytesRead is a pointer to a integer variable that will hold the number of bytes */
    /*           actually received from the sender. */
    /* The function returns either the number of bytes read, */
    /*                             0 if the socket was closed by the sender, and */
    /*                            -1 if an error occurred while reading from the socket */
    int readBytes(int socket, char *buffer, int bytesToRead, int *bytesRead)
    {
        *bytesRead = 0;
        while(*bytesRead < bytesToRead)
        {
            int ret = read(socket, buffer + *bytesRead, bytesToRead - *bytesRead);
            if(ret <= 0)
            {
               /* either connection was closed or an error occurred */
               return ret;
            }
            else
            {
               *bytesRead += ret;
            }
        }
        return *bytesRead;
    }
    

提交回复
热议问题