본문 바로가기

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

[네트워크] 가변 구조체 전송

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개이상이면, 패킷을 두개이상으로 나눠보내는 것이 좋다

 

 


 

 

struct empty
{
unsigned long fname_size;
char fname[0];
};

int main(void)
{
struct empty emp;
char *str = "hello";
int i;

for( i = 0; i < strlen( str ); i++ )
{
emp.fname[ i ] = *(str + i );
}
emp.fname[ i ] = 0;
emp.fname_size = i;


printf( "fname_size: %lu\n", emp.fname_size );
printf( "fname : %s\n", emp.fname );
printf( "empty size: %d\n", sizeof( emp ) );

return 0;
}


 *가변구조체

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

 

= http://spanthoma.egloos.com/1511185

 

* 메모리 할당방법

#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;
}

'개발 언어 > C 언어/리눅스 C' 카테고리의 다른 글

쓰레드 관련 모음  (0) 2012.09.05
프로토콜 설계  (0) 2012.08.31
How GDB  (0) 2012.08.24
데몬 만들기  (0) 2012.08.21
시그널 처리방법  (0) 2012.08.21