Pergunta

I'm reading a packet but I need to strip the first four bytes and the last byte from the packet to get what I need, how would you go about doing this in C?

/* Build an input buffer of the incoming message. */
    while ( (len=read(clntSocket, line, MAXBUF)) != 0)
    {
            msg = (char *)malloc(len + 1);
            memset(msg, 0, len+1);
            strncpy(msg, line, len);
        }
    }

The incoming data is a mix of char and int data.

Foi útil?

Solução

You can change the address of strncpy source:

while ( (len=read(clntSocket, line, MAXBUF)) != 0)
{
        msg = (char *)calloc(len -3, 1); // calloc instead of malloc + memset
        strncpy(msg, line+4, len);
    }
}

PS: I assumed that line is char*.

Outras dicas

You can simply start you copy at (line + 4) if line is a char *, which it appears to be. And copy 5 bytes fewer than len, which will ditch the last byte.

I.e. making it pretty explicit (assuming your prior malloc, which leaves some safety at the end of the buffer).

char *pFourBytesIn = (line + 4);
int adjustedLength = len - 5;
strncpy(msg, pFourBytesIn, adjustedLength);
msg[adjustedLength] = '\0';
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top