ccs.c 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. // raw_sock.c
  2. #include<stdio.h>
  3. #include<stdlib.h>
  4. #include<string.h>
  5. #include<netinet/ip.h>
  6. #include<sys/socket.h>
  7. #include<arpa/inet.h>
  8. #include <unistd.h>
  9. int main() {
  10. // Structs that contain source IP addresses
  11. struct sockaddr_in source_socket_address, dest_socket_address;
  12. int packet_size;
  13. struct timeval tv;
  14. // Allocate string buffer to hold incoming packet data
  15. unsigned char *buffer = (unsigned char *)malloc(65536);
  16. // Open the raw socket
  17. int sock = socket (PF_INET, SOCK_RAW, IPPROTO_TCP);
  18. tv.tv_sec = 0;
  19. tv.tv_usec = 10000;
  20. if (setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(struct timeval)) < 0)
  21. {
  22. #ifdef SystemLogMessage
  23. StoreLogMsg("[PsuCOmm]InitCanBus:Set SO_RCVTIMEO NG");
  24. #endif
  25. }
  26. if(sock == -1)
  27. {
  28. //socket creation failed, may be because of non-root privileges
  29. printf("Failed to create socket\n");
  30. return 1;
  31. }
  32. while(1) {
  33. // recvfrom is used to read data from a socket
  34. packet_size = recvfrom(sock , buffer , 65536 , 0 , NULL, NULL);
  35. if (packet_size == -1)
  36. {
  37. printf("Failed to get packets\n");
  38. sleep(5);
  39. continue;
  40. }
  41. printf("get packets, packet_size=%d\n",packet_size);
  42. struct iphdr *ip_packet = (struct iphdr *)buffer;
  43. memset(&source_socket_address, 0, sizeof(source_socket_address));
  44. source_socket_address.sin_addr.s_addr = ip_packet->saddr;
  45. memset(&dest_socket_address, 0, sizeof(dest_socket_address));
  46. dest_socket_address.sin_addr.s_addr = ip_packet->daddr;
  47. printf("Incoming Packet: \n");
  48. printf("Packet Size (bytes): %d\n",ntohs(ip_packet->tot_len));
  49. printf("Source Address: %s\n", (char *)inet_ntoa(source_socket_address.sin_addr));
  50. printf("Destination Address: %s\n", (char *)inet_ntoa(dest_socket_address.sin_addr));
  51. printf("Identification: %d\n\n", ntohs(ip_packet->id));
  52. }
  53. return 0;
  54. }