Develop
네트워크 각 헤더의 Next Type 파싱하기.
Dork94
2017. 9. 25. 16:05
우리가 네트워크 프로그래밍 하다 보면, 원하는 헤더의 정보를 얻기위해 이더넷 헤더부터 또는 ip헤더(3계층 헤더)부터 데이터를 탐색해 나가야 하는 경우가 있는데 이 작업이 반복적이고 빈번하므로 함수로 만들어 두는 것이 좋다.
그래서 내가 만들어 놓은 함수를 공유 하고자 한다.
아래의 소스코드로 간단하게 주소 헤더의 형태 및 해당 헤더로 포인터를 이동 시킬 수 있다.
bool형으로 true가 리턴 될 경우 type(IPPROTO_TCP 등)에 대한 헤더의 첫 포인터를 가르키게 되며, false일 경우 해당 포인터의 이동이 없다.
또한, TCP의 경우 데이터의 부분을 파싱할 수 있고, data의 길이가 없을 경우 false가 리턴된다,
#include <iostream> #include <netinet/in.h> #include <netinet/ether.h> #include <netinet/ip.h> #include <netinet/tcp.h> bool parseEther(uint8_t** data,int& dataLen,int type) { struct ether_header *ep=(struct ether_header*)*data; if(ntohs(ep->ether_type)==type) { *data=*data+sizeof(struct ether_header); dataLen-=sizeof(struct ether_header); return true; } return false; } bool parseIP(uint8_t** data,int& dataLen, int type) { struct iphdr *iph=(struct iphdr*)*data; if(iph->protocol==type) { *data=*data+(iph->ihl*4); dataLen-=(iph->ihl*4); return true; } return false; } bool parseTCPData(uint8_t **data, int &dataLen) { struct tcphdr* tcph = (struct tcphdr*)*data; *data=*data+(tcph->doff*4); dataLen-=(tcph->doff*4); if(dataLen<=0) return false; else return true; }