How to send an integer through a socket?

I am trying to send an integer through a socket. I use this code for this; however, my C code will not compile. The compiler complains that myInt has not been declared.

int tmp = htonl(myInt);
write(socket, &tmp, sizeof(tmp));

How to declare myInt? Thank.

+3
source share
4 answers

Are you sure that it was correctly declared in your program?

Try it like this:

int myInt = something;    
int tmp = htonl((uint32_t)myInt);
write(socket, &tmp, sizeof(tmp));
+5
source

You may need to just spend some time learning the basics of C before dealing with the socket library.

You need to declare myInt as an integer variable as follows:

  int myInt;

, "myInt", int. , myInt .

:

  int myInt = 0;
+1

One simple solution: typecase integer before char and send 4 bytes of char buffer

int myInt char * ptr = & myInt; write (socket, ptr, sizeof (int));

read 4 bytes at the end of the record. You will not have problems with enthusiasm.

-2
source

Convert everything to char, you don’t have to worry about endianness, because it charis a byte, instead read it byte.

-2
source

All Articles