#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
char* createMSG(uint8_t i,uint32_t port);
int strlen(char* tmp);
uint32_t user_port = 5000;
int main(int argc, char** argv) {
char *msg;
uint8_t i;
i = 1;
msg = createMSG(i,user_port);
printf("Port: %d",*(msg+2));
}
char* createMSG(uint8_t i,uint32_t port) {
char *buff;
buff = (char*) malloc(6);
uint8_t id;
id = 2;
memcpy(buff, &id, sizeof(uint8_t));
memcpy(buff+1, &i, sizeof(uint8_t));
memcpy(buff+2, &port, sizeof(uint32_t));
return buff;
}
The output is: "Port: -120". It seems there is some overflow. But uint32_t should be big enough for 5000. When using 22 instead of 5000, everything is ok.
Why?
This line
prints the 'char' value at (msg+2) address, not the uint32_t !
Use
To "fix" port numbers from recvfrom() function one must use the ntohl() function.