#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
// 检查是否为有效的组播IP地址
int is_valid_multicast_ip(const char *ip) {
struct in_addr addr;
if (inet_pton(AF_INET, ip, &addr) <= 0) {
return 0;
}
unsigned char *octets = (unsigned char *)&addr.s_addr;
return (octets[0] >= 224 && octets[0] <= 239);
}
// 检查是否为有效的端口号
int is_valid_port(const char *port_str) {
char *endptr;
long port = strtol(port_str, &endptr, 10);
if (*endptr != '\0' || port < 1024 || port > 65535 ) {
return 0;
}
return 1;
}
// 检查字符串是否符合组播IP:组播端口格式
int is_valid_multicast_ip_port(const char *str) {
char ip[INET_ADDRSTRLEN];
char port_str[6];
char *colon = strchr(str, ':');
if (colon == NULL) {
return 0;
}
size_t ip_len = colon - str;
if (ip_len >= INET_ADDRSTRLEN) {
return 0;
}
strncpy(ip, str, ip_len);
ip[ip_len] = '\0';
size_t port_len = strlen(colon + 1);
if (port_len >= 6) {
return 0;
}
strcpy(port_str, colon + 1);
return is_valid_multicast_ip(ip) && is_valid_port(port_str);
}
int main() {
//char *temp_string = "rqwer";
char *temp_string = NULL;
const char *test_strings[] = {
"224.0.0.1:8888",
"192.168.1.1:8888",
"224.0.0.1:65536",
"224.0.0.1:abc",
"224.0.0.0:522",
"223.0.0.0:1024",
"240.0.0.1:1024",
"224.0.0.1:8888:",
":224.0.0.1:8888",
":1233",
"224.0.0.1",
":"
};
for (int i = 0; i < sizeof(test_strings) / sizeof(test_strings[0]); i++) {
if (is_valid_multicast_ip_port(test_strings[i])) {
printf("%s 是有效的组播IP:组播端口格式\n", test_strings[i]);
} else {
printf("%s 不是有效的组播IP:组播端口格式\n", test_strings[i]);
}
}
//is_valid_multicast_ip_port(NULL); //不能输入NULL
if ((temp_string != NULL)&&(is_valid_multicast_ip_port(temp_string)))
{
printf("%s 是有效的组播IP:组播端口格式\n",temp_string);
}
else
{
printf("%s 不是有效的组播IP:组播端口格式\n",temp_string);
}
return 0;
}
今天用ai实现了一个功能,c语言检验字符串是否符合ip:端口模式,如果让我自己来写的话,估计得三四个小时,这个几秒钟的功夫,太省心了,水篇文章做个纪念吧。
所以当今的程序员比过去的要更幸运吧。

被折叠的 条评论
为什么被折叠?



