用C语言检验字符串是否符合ip:端口模式(ai写的)

#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:端口模式,如果让我自己来写的话,估计得三四个小时,这个几秒钟的功夫,太省心了,水篇文章做个纪念吧。

所以当今的程序员比过去的要更幸运吧。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值