写入和读取 - 插座AF_UNIX

时间:2013-12-17 20:52:12

标签: c sockets

我正在为大学做一个项目。需要编写套接字的代码和一个服务器以及一个与此套接字相关联的客户端。 Messagges就像:

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

我编写了Socket代码,现在我遇到了两个函数问题:sendMessage和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;
   }

这是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;

}

测试返回receiveMessage的INVALID ARGUMENT并且没有消息在套接字中写入和读取,我认为问题在于缓冲区的长度(unsigned int) 有什么建议?

1 个答案:

答案 0 :(得分:2)

检查联机帮助页以了解有关EINVAL的内容,您要么发送无效的套接字,要么发送无效的read()指针。尝试调试哪个read()调用也失败了。

然而这是错误的:

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

你的缓冲区是一个指针,你想要在任何地方读取数据,而不是它的地址。所以它应该是

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