Advertisement
Guest User

Untitled

a guest
Sep 3rd, 2015
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.96 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include<sys/types.h>
  4. #include<sys/socket.h>
  5. #include<errno.h>
  6. #include<net/if.h>
  7. #include<net/ethernet.h>
  8. #include<netinet/ip.h>
  9. #include<netinet/tcp.h>
  10.  
  11. int sock;
  12.  
  13. //プロトタイプ宣言
  14. void PacketAnalysis(u_char* buf);
  15. void printEtherHeader(u_char* buf);
  16. void printIPHeader(u_char* buf);
  17. void printTCPHeader(u_char* buf);
  18.  
  19. int main(int argc,char* argv[]){
  20. u_char buf[65535];
  21. sock = socket(PF_PACKET,SOCK_RAW,htons(ETH_P_ALL));
  22. if(sock<0){
  23. perror("socket");
  24. printf("%d\n",errno);
  25. return 1;
  26. }
  27. //ループ内でデータを受信し、解析用の関数に渡す
  28. while(1){
  29. read(sock,buf,sizeof(buf));
  30. PacketAnalysis(buf);
  31. }
  32.  
  33. return 0;
  34. }
  35. //パケット解析用関数
  36. void PacketAnalysis(u_char* buf){
  37. u_char* pack;
  38. struct ether_header *eth;
  39. struct iphdr *ip;
  40. pack=buf;
  41. eth=(struct ether_header *)buf;
  42. pack+=sizeof(struct ether_header);
  43. printf("type:");
  44. switch(ntohs(eth->ether_type)){
  45. case ETH_P_IP:
  46. printf("ETH_P_IP\n");
  47. printIPHeader(pack);
  48. ip=(struct iphdr *)pack;
  49. if(ip->protocol==6){//ipv6の時
  50. pack+=((struct iphdr *)pack)->ihl*4;
  51. printTCPHeader(pack);
  52. }
  53. break;
  54. case ETH_P_IPV6:
  55. printf("IPv6\n");
  56. break;
  57. case ETH_P_ARP:
  58. printf("ETH_P_ARP\n");
  59. break;
  60. default:
  61. printf("unknown\n");
  62. break;
  63. }
  64. }
  65.  
  66. //ipヘッダーを表示する関数
  67. void printIPHeader(u_char* buf){
  68. struct iphdr *ip;
  69. ip=(struct iphdr *)buf;
  70. printf("-----IP header-----\n");
  71. printf("version:%u\n",ip->version);
  72. printf("Interner header length:%x\n",ip->ihl);
  73. printf("type of service:%x\n",ip->tos);
  74. printf("total length:%u\n",ntohs(ip->tot_len));
  75. printf("id:%u\n",ntohs(ip->id));
  76. printf("time to live:%u\n",ip->ttl);
  77. printf("protocol:%u\n\n",ip->protocol);
  78. }
  79.  
  80. //tcpヘッダーを表示する関数
  81. void printTCPHeader(u_char* buf){
  82. struct tcphdr *tcp;
  83. tcp = (struct tcphdr *)buf;
  84. printf("-----TCP Header----\n");
  85. printf("source port:%u\n",ntohs(tcp->source));
  86. printf("dest port:%u\n\n",ntohs(tcp->dest));
  87. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement