user2995645
user2995645

Reputation:

Read value from variable

I am trying to assign a string or an int to msg to send it later to a server. This code is in the client.

  char msg[100];
    int a;
    .
    .
    .
      bzero (msg, 100);
      printf ("[client]your message: ");
      fflush (stdout);
      read (0, msg, 100);

      /* sending message to server */
      if (write (sd, msg, 100) <= 0)
        {
          perror ("[client]Error write() to server.\n");
          return errno;
        }

My question is how can I send the variable 'a', instead of writing a message from the command line.

Upvotes: 0

Views: 87

Answers (2)

Mike
Mike

Reputation: 49373

I think you're a little confused about what is going on in your program. First, let's start with write().

The signature for the write() function is as follows:

ssize_t write(int fd,            // a file descriptor 
              const void *buf,   // a void * containing the payload
              size_t count       // the number of bytes of data to write
             ); 

So what you have right now is:

  read (0, msg, 100);  // read from stdin a ascii message up to 100 bytes

  /* sending message to server */
  if (write (sd, msg, 100) <= 0)  // write to a file descriptor (sd) the message
                                  // if it works, it should return the number of bytes
                                  // written

Now as far as I can tell, what you're saying is that you want to send the integer a instead of the char buffer msg. That's very easy to do:

int a = 0;
write(sd, &a, sizeof(a)); // send over the file descriptor "sd"
                          // you need a pointer for the second variable so use the &
                          // to get the address of a, then you need to identify
                          // the number of bytes to send, so use the sizeof macro

That will send a single integer over the socket.

You will likely need to be careful of endian issues using this approach for multibyte values (such as integers). From that perspective you might be better using an array of chars (shift in the values) so you know what to expect on the other end.


To be very blunt:

int a = rand();      // a random integer (assuming required headers and proper seeding)
char *msg = "Hello"; // a string

write(sd, &a, sizeof(a));       // write the integer
write(sd, msg, strlen(msg)+1);  // write a string (strlen + 1 for the null terminator)

Upvotes: 0

Ron Burk
Ron Burk

Reputation: 6231

sprintf(msg, "%d\n", a);
...
write(sd, msg, strlen(msg));

This assumes the client is expecting a string of digits (representing an integer) followed by a newline. I arbitrarly chose a newline delimiter, but you must have some convention by which the server knows what the heck you're sending.

Upvotes: 1

Related Questions