user2590319
user2590319

Reputation: 3

Write and Read - Socket AF_UNIX

i'm doing a project for University. Need to write the code of a socket and one server and one client that talk trought this socket. Messagges are like:

typedef struct {
  /** message type */
    char type;           
  /** message length in byte */
    unsigned int length; 
  /** message buffer */
    char *buffer;        
  } message_t; 

I wrote code of Socket and now i'm having problems with two function :sendMessage and receiveMessage

    /** read a message from the socket --- properly split the message and put it in the struct message_t 
 *  \param  sc  file descriptor of the socket
 *  \param msg  
 *
 *  \retval lung  length of the buffer read, if it's OK 
 *  \retval  -1   if there are errors (set errno)
 *                
 *      
 */
int receiveMessage(int sc, message_t * msg) {

  int lung;

  lung = read(sc, &(msg->type), sizeof(char));
  if(lung == 0) 
    return -1;
  if(lung == -1)
    return -1;

  lung = read(sc, &(msg->length), sizeof(unsigned int));
  if(lung == 0)
    return -1;
  if(lung == -1)
    return -1;

  if(msg->length > 0) {

    msg->buffer = malloc (sizeof(char)*msg->length);

    lung = read(sc, &(msg->buffer), sizeof(char)*msg->length);
    if(lung == 0)
      return -1;
    if(lung == -1)
      return -1;
  }
  return lung;
   }

This is sendMessage

/** write a message on the socket --- should send only significant byte of the buffer    (msg->length byte) --  must use only 1 write
 *   \param  sc file descriptor of the socket
 *   \param msg address of the struct 
 *   
 *   \retval  n    no. of char sent (if its OK)
 *   \retval -1   if there are errores (set errno)
 *                  
 *                  
 */
int sendMessage(int sc, message_t *msg) {

  int n,lung;

  lung = sizeof(unsigned int) + sizeof(char) + (sizeof(char)*msg->length);

  record = malloc (lung);

  sprintf(record,"%c%u%s",msg->type,msg->length,msg->buffer);

  n = write(sc,record,lung);
  if(n == 0) 
    return -1;
  return n;

}

Test return INVALID ARGUMENT of the receiveMessage and no message are write and read in the socket, i think the problem is with length of buffer (an unsigned int) Any advice?

Upvotes: 0

Views: 798

Answers (1)

nos
nos

Reputation: 229058

Check the manpage for read on what it says about EINVAL, you're either sending in an invalid socket, or an invalid pointer to read(). Try to debug which of your read() call that fails too.

However this is wrong:

lung = read(sc, &(msg->buffer), sizeof(char)*msg->length);

Your buffer is a pointer, and you want to read the data wherever that points, not to its address. So it should be

lung = read(sc, msg->buffer, sizeof(char)*msg->length);

Upvotes: 2

Related Questions