본문 바로가기

개발 언어/C 언어/리눅스 C

[네트워크] 동적구조체 전달 방법 (가번구조체 추가)

■ 가변구조체 참고 링크

http://blog.naver.com/PostView.nhn?blogId=sdi760210&logNo=70084541983&parentCategoryNo=63&viewDate=&currentPage=1&listtype=0

 

http://spanthoma.egloos.com/1511185



■ 방법1. 배열 길이를 선언하고 기록한 데이터 크기만 전송하기


struct MyData 
{
int data_size;
int data1;
int data2;
char string_data[5000];
};


char *p_string = "abcdefg";

MyData send_data;

send_data.data_size = sizeof(int)*2 + strlen(p_string)+1;
strcpy(send_data.string_data, p_string);
p_socket->send(&send_data, sizeof(int)*3 + strlen(p_string) + 1);


 

팁 => 가변 데이터는 size 변수 뒤로 보낸다

설명 => 구조체는 정적이지만, 전송루틴을 동적으로 생성하여 전송

읽기 => 처음 4바이트를 먼저 읽어 뒤의 데이터 크기를 읽어서 나머지 데이터를 읽어들이면 된다.

한계 => 가변이 2개이상이면, 패킷을 두개이상으로 나눠보내는 것이 좋다

 

 


 

 ■ 방법2. 가변구조체 사용1 - 비표준

 - 구조체 배열을 할당하여 사용하지 않는다면, 로컬변수의 주소와 겹칠수 있는 잠재적인 위험이 있다


typedef struct dinamic {

int len;

char str[0];

}dinamic_t;


int main(void)
{

dinamic_t nopd;
printf("pre_size:%d\n", sizeof(dinamic_t));
nopd.len = strlen(path);
strcpy(nopd.str, path);
printf("after strcpy:%d\n", sizeof(nopd));
printf("path:%s\n", nopd.str);

}


pre_size:4
after strcpy:4
path:/root/test




■ 방법3. 가변구조체 동적할당 - 표준 

- 안전한 방법


#include <stdio.h>
#include "stdlib.h"

struct A {
int a;
int b[];
};

int main()
{
const int N = 10;
int i;

struct A* p = (A*)malloc(sizeof(struct A) + sizeof(int) * (N - 1));

p->a = 100;
for (i = 0; i < N; i++)
{
p->b[i] = i;
}

printf("%d %d %d\n", p->a, p->b[0], p->b[N-1]);
for( int loop = 0 ; loop < N + 1 ; loop++ )
{
printf("%d %d\n", p->a, p->b[loop]);

system("pause");
//free(p);

return 0; 


또는,


typedef struct dinamic {

int len;

char str[];

}dinamic_t;

int main(void) {

puts("!!!Hello World!!!"); /* prints !!!Hello World!!! */



/*

 *  동적할당하여 안전하게 사용하는 방법

 */

char *path = "/root/test";

printf("pre_size:%d\n", sizeof(dinamic_t));

dinamic_t *d = (dinamic_t *)malloc( sizeof(dinamic_t) + strlen(path));


d->len = strlen(path);

strcpy(d->str, path);

printf("malloc_size:%d\n", sizeof(d));

printf("path:%s\n", d->str);

free(d);

}