使用Linux 原始套接字抓取数据链路层上IEC61850-9-2(LE) SV数据包并显示的参考程序

来源:互联网 发布:女士休闲鞋新款淘宝网 编辑:程序博客网 时间:2024/05/22 06:21
目标:在linux下使用C语言的原始套接字来接收以太网数据链路层上的数据,如果接收的数据是IEC61850-9-2 SV类型,则打印。。。。仅供参考!

源代码:

[cpp] view plaincopy
  1. #include <stdio.h>  
  2. #include <unistd.h>  
  3. #include <sys/socket.h>  
  4. #include <sys/types.h>  
  5. #include <linux/if_ether.h>  
  6. #include <linux/in.h>  
  7. #define BUFFER_MAX 2048  
  8.   
  9. int main(int argc, char *argv[])  
  10. {        
  11. int sock, n_read, eth_type;          
  12. char buffer[BUFFER_MAX];  
  13. char  *eth_head;  
  14.          
  15. if((sock = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL))) < 0)  
  16. {  
  17.     fprintf(stdout, "create socket error/n");  
  18.         exit(0);  
  19. }  
  20.           
  21. while(1)   
  22. {  
  23.     n_read = recvfrom(sock, buffer, 2048, 0, NULL, NULL);  
  24.     if(n_read < 42)   
  25.     {  
  26.         fprintf(stdout, "Incomplete header, packet corrupt/n");  
  27.         continue;  
  28.     }  
  29.                  
  30.     eth_head = buffer;  
  31.     eth_type=((unsigned char)eth_head[16])*16*16+(unsigned char)eth_head[17];  
  32.       
  33.     if(eth_type==0x88ba){    //judge wether the eth_type is iec61850 sv  
  34.         printf("\n----------------IEC61850-9-2 SV---------------------\n");  
  35.             int i=0;  
  36.         for(i=0;i<n_read;i++){  
  37.             printf("%.2X ",(unsigned char)eth_head[i]);  
  38.             if(((i+1)%16)==0) printf("\n");  
  39.         }  
  40.         printf("\n----------------------------------------------------\n");  
  41.     }  
  42. }  
  43. }  

运行效果:


(------------------完---------------------)

0 0
原创粉丝点击