2016년 5월 5일 목요일

뇌자극 TCP_IP 프로그래밍 6강 요약

세상에는 수많은 컴퓨터가 있고, 수많이 연결되어 있다.
그러다 보니 데이터를 처리하는 방식이 다른 경우가 많다.
인터넷으로 돌아다닐 데이터는 상대방 컴퓨터가 어떤 CPU를 쓰는지 모른다.
그래서 이것을 통일 시켜줘야 한다.

서로 다른 데이터 읽는 방식의 교류를 위해 "네트워크 바이트 순서" 를 정했다.
인터넷으로 데이터를 보낼 때는 무조건 네트워크 바이트 순서로 변환해서 내보내야 한다.

바이트 순서 변환 함수는 다음과 같다

#include <netinet/in.h>

unsigned long int htonl(unsigned long int hostdata)
unsigned short int htons(unsigned short int hostdata)

unsigned long int ntohl(unsigned long int netdata)
unsigned short int ntohs(unsigned short int netdata)

자세히 보면 일정한 패턴이 있다.

데이터를 보낼 때
htonl = host to network (long)
htons = host to network (short)

데이터를 받을 때
ntohl = network to host (long)
ntohs = network to host (short)

예제)
//쓸 때 (보낼 때)
mydata.age = htons(25);
mydata.birthday = htonl(19811203);

//읽을 때 (받을 때)
read((void*)&mydatainfo, .....);
ntohs(mydatainfo.age);
ntohl(mydatainfo.birthday);

댓글 없음:

댓글 쓰기