ctorrent stat collector
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

100 lines
1.8KB

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <sys/types.h>
  5. #include <sys/socket.h>
  6. #include <netinet/in.h>
  7. #include <arpa/inet.h>
  8. int parse_sockaddr(const char *addr, struct sockaddr_in *sa)
  9. {
  10. char *buf = strdup(addr);
  11. if (buf == NULL)
  12. return -1;
  13. char *tmp;
  14. char *ipstr = strtok_r(buf, ":", &tmp);
  15. if (ipstr == NULL) {
  16. free(buf);
  17. return -2;
  18. }
  19. sa->sin_family = AF_INET;
  20. if (inet_pton(AF_INET, ipstr, &sa->sin_addr) <= 0) {
  21. free(buf);
  22. return -3;
  23. }
  24. char *portstr = strtok_r(NULL, " \r\n", &tmp);
  25. if (portstr == NULL) {
  26. free(buf);
  27. return -4;
  28. }
  29. int port = atoi(portstr);
  30. if (port < 0 || port > 65535) {
  31. free(buf);
  32. return -5;
  33. }
  34. sa->sin_port = htons(port);
  35. free(buf);
  36. return 0;
  37. }
  38. int parse_subnet(const char *addr, struct in_addr *net, struct in_addr *mask)
  39. {
  40. char *buf = strdup(addr);
  41. if (buf == NULL)
  42. return -1;
  43. char *tmp;
  44. char *netstr = strtok_r(buf, "/", &tmp);
  45. if (netstr == NULL) {
  46. free(buf);
  47. return -2;
  48. }
  49. if (inet_pton(AF_INET, netstr, net) <= 0) {
  50. free(buf);
  51. return -3;
  52. }
  53. char *maskstr = strtok_r(NULL, " \r\n", &tmp);
  54. if (maskstr == NULL) {
  55. mask->s_addr = ~0;
  56. } else if (inet_pton(AF_INET, maskstr, mask) <= 0) {
  57. int maskbits = atoi(maskstr);
  58. if (maskbits < 0 || maskbits > 32) {
  59. free(buf);
  60. return -4;
  61. }
  62. mask->s_addr = htonl(~0 << (32 - maskbits));
  63. }
  64. free(buf);
  65. return 0;
  66. }
  67. int get_sockaddr(char *buf, int size, struct sockaddr_in *addr)
  68. {
  69. return snprintf(buf, size, "%s:%d", inet_ntoa(addr->sin_addr), ntohs(addr->sin_port));
  70. }
  71. char * get_sockaddr_buf(struct sockaddr_in *addr)
  72. {
  73. static char ret[24];
  74. get_sockaddr(ret, sizeof(ret), addr);
  75. return ret;
  76. }
  77. int same_sockaddr(struct sockaddr_in *a, struct sockaddr_in *b)
  78. {
  79. return !((a->sin_family ^ b->sin_family) |
  80. (a->sin_addr.s_addr ^ b->sin_addr.s_addr) |
  81. (a->sin_port ^ b->sin_port));
  82. }