题解 | #识别有效的IP地址和掩码并进行分类统计#
识别有效的IP地址和掩码并进行分类统计
https://www.nowcoder.com/practice/de538edd6f7e4bc3a5689723a7435682
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <stdbool.h> #include <sys/socket.h> #include <errno.h> #include <netinet/in.h> #include <arpa/inet.h> static bool check_mac(struct in_addr mac_addr) { int i = ntohl(mac_addr.s_addr); if (i == 0 || i == 0xffffffff) { return false; } if ((i | i - 1) == 0xffffffff) { return true; } return false; } static void check_ip(char* ip, int* ret) { // printf("%s\n", ip); int num = atoi(ip); if (num > 0 && num < 127) { ret[0]++; } else if (num > 127 && num < 192) { ret[1]++; } else if (num > 191 && num < 224) { ret[2]++; } else if (num > 223 && num < 240) { ret[3]++; } else if (num > 239 && num < 256) { ret[4]++; } if (num == 10) { ret[6]++; } if (num == 172) { char* ch = strchr(ip, '.'); if (ch != NULL) { int num1 = atoi(ch + 1); if (num1 > 15 && num1 < 32) { ret[6]++; } } } if (num == 192) { char* ch = strchr(ip, '.'); if (ch != NULL) { int num1 = atoi(ch + 1); if (num1 == 168) { ret[6]++; } } } } int main() { char str[32] = {0}; int ret[7] = {0}; char ip[16] = {0}; char mac[16] = {0}; struct in_addr ip_addr; struct in_addr mac_addr; while (scanf("%s", str) != EOF) { if (atoi(str) == 0 || atoi(str) == 127) { memset(str, 0, sizeof(str)); continue; } char* ch = strchr(str, '~'); memcpy(ip, str, ch - str); memcpy(mac, ch + 1, (str + strlen(str)) - ch - 1); if (inet_aton(ip, &ip_addr) == 0 || inet_aton(mac, &mac_addr) == 0 || !check_mac(mac_addr)) { // printf("%s\n", ip); ret[5]++; } else { check_ip(ip, ret); } memset(str, 0, sizeof(str)); memset(ip, 0, sizeof(ip)); memset(mac, 0, sizeof(mac)); } for (int i = 0; i < 7; i++) { printf("%d ", ret[i]); } return 0; }