2017-11-13 1 views
0

C에서 간단한 서버 클라이언트 프로그램을 만들려고합니다. 클라이언트에서 서버에서 메시지를 수신하려고 시도하지만, 메시지의 크기는 미리 결정되지 않습니다. 따라서 들어오는 바이트 수를 확인하고 적절한 크기 인 malloc을 확인하고 싶습니다.ioctl(), read() 및 malloc()을 사용하여 서버가 제대로 작동하지 않는 경우 메시지 수신

나는 ioctl을 사용하려고했지만, 너무 늦은 정보를 얻는 것처럼 보입니다. 이것은 내가 가지고있는 것입니다.

char *message_from_server; 
int length; 
while(1){ 
    ioctl(socket, FIONREAD, &length); 
    message_from_server = malloc(length); 
    read(socket, message_from_server, length); 
} 

I 처음 사용할 때, length이 0 번째 시간 길이는 첫 번째 메시지의 것과 동일하다. 내가 읽은 후에 라인 ioctl(socket, FIONREAD, &length);을 넣으면, 정확한 공간을 mallocing하는 데 어려움을 겪을 수 있습니다. 이 문제가 내 문제를 해결하는 유효한 방법일까요?

나는 내 문제를 해결하기 위해 realloc을 사용할 수 있다고 들었지만, 어떻게 내 문제를 해결할 수 있는지 보려고 고심 중이다. 그게 더 좋은 방법이라면, 나는 어떤 조언도 기뻐할 것입니다.

감사합니다.

+0

TCP 만 있으면 수신 데이터의 크기가 미리 결정됩니다. 1 바이트 이상이 될 것입니다. ioctl을 사용하여 "peeking"하여 하나 이상의 바이트로 응용 프로그램 메시지를 구현하려는 경우 또는 read()가 항상 1 바이트보다 긴 완전한 메시지로 버퍼를로드한다고 가정하면 곧 문제가 발생할 것입니다. –

답변

1

realloc을 사용하면 내용을 보존하면서 메모리 블록의 크기를 늘릴 수 있습니다.

따라서, 귀하의 경우 : 들어오는 패킷의

  1. 읽기 크기
  2. 매장 패킷에
  3. 업데이트 메모리 블록,
  4. 가 패킷을 읽어
  5. 고토 1. 또는 이전에 무엇을 읽은 보존

    : 출구

코드는 같아야합니다

/* memory to store message, initially, no memory */ 
char *message_from_server = NULL; 
/* size of memory */ 
int total_length = 0; 

/* sizeof incoming packet*/ 
int packet_lentgh; 

/* position to write in memory */ 
int offset; 

while(1){ 
    /* read size of incoming packet*/ 
    ioctl(socket, FIONREAD, &packet_lentgh); 

    if (0 != packet_lentgh) 
    { 
     /* something is ready to be read on socket */ 

     /* update memory size */ 
     total_length += packet_lentgh; 

     /* allocate much memory*/ 
     message_from_server = realloc(message_from_server, total_length); 
     if (NULL == message_from_server) 
     { 
      perror("realloc"); 
      abort(); 
     } 

     /* compute the position to write in memory */ 
     offset = total_length - packet_lentgh; 

     /* read the packet */ 
     read(socket, message_from_server + offset, packet_lentgh); 
    } 
    else 
    { 
     /* nothing to read 
      wait for packet or stop loop... */ 
    } 
} 
+0

늦게 답변드립니다. 고맙습니다! – tore

관련 문제