Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<stdio.h>
- #include<stdlib.h>
- #include<sys/types.h>
- #include<sys/socket.h>
- #include<errno.h>
- #include<net/if.h>
- #include<net/ethernet.h>
- #include<netinet/ip.h>
- #include<netinet/tcp.h>
- int sock;
- //プロトタイプ宣言
- void PacketAnalysis(u_char* buf);
- void printEtherHeader(u_char* buf);
- void printIPHeader(u_char* buf);
- void printTCPHeader(u_char* buf);
- int main(int argc,char* argv[]){
- u_char buf[65535];
- sock = socket(PF_PACKET,SOCK_RAW,htons(ETH_P_ALL));
- if(sock<0){
- perror("socket");
- printf("%d\n",errno);
- return 1;
- }
- //ループ内でデータを受信し、解析用の関数に渡す
- while(1){
- read(sock,buf,sizeof(buf));
- PacketAnalysis(buf);
- }
- return 0;
- }
- //パケット解析用関数
- void PacketAnalysis(u_char* buf){
- u_char* pack;
- struct ether_header *eth;
- struct iphdr *ip;
- pack=buf;
- eth=(struct ether_header *)buf;
- pack+=sizeof(struct ether_header);
- printf("type:");
- switch(ntohs(eth->ether_type)){
- case ETH_P_IP:
- printf("ETH_P_IP\n");
- printIPHeader(pack);
- ip=(struct iphdr *)pack;
- if(ip->protocol==6){//ipv6の時
- pack+=((struct iphdr *)pack)->ihl*4;
- printTCPHeader(pack);
- }
- break;
- case ETH_P_IPV6:
- printf("IPv6\n");
- break;
- case ETH_P_ARP:
- printf("ETH_P_ARP\n");
- break;
- default:
- printf("unknown\n");
- break;
- }
- }
- //ipヘッダーを表示する関数
- void printIPHeader(u_char* buf){
- struct iphdr *ip;
- ip=(struct iphdr *)buf;
- printf("-----IP header-----\n");
- printf("version:%u\n",ip->version);
- printf("Interner header length:%x\n",ip->ihl);
- printf("type of service:%x\n",ip->tos);
- printf("total length:%u\n",ntohs(ip->tot_len));
- printf("id:%u\n",ntohs(ip->id));
- printf("time to live:%u\n",ip->ttl);
- printf("protocol:%u\n\n",ip->protocol);
- }
- //tcpヘッダーを表示する関数
- void printTCPHeader(u_char* buf){
- struct tcphdr *tcp;
- tcp = (struct tcphdr *)buf;
- printf("-----TCP Header----\n");
- printf("source port:%u\n",ntohs(tcp->source));
- printf("dest port:%u\n\n",ntohs(tcp->dest));
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement