判断ip

来源:互联网 发布:linux计数统计文件命令 编辑:程序博客网 时间:2024/06/10 07:53
#include <sys/types.h>#include <sys/socket.h>#include <netinet/in.h>#include <arpa/inet.h>#define IPV4 1#define IPV6 2int is_ip(const char *ip, int ip_type){struct in_addr  ipv4;struct in6_addr ipv6;int ret;if (ip_type == IPV4) {ret = inet_pton(AF_INET, ip, &ipv4);} else {ret = inet_pton(AF_INET6, ip, &ipv6);}if (ret > 0)printf("%s is a valid IPv4 address\n", ip);else if (ret < 0)        printf("EAFNOSUPPORT: %s\n", ip);else printf("%s is not a valid IPv4 address\n", ip);return ret;}int main(){char buf[] = "1.1.1.1";char buf2[] = "1.1.1.";char buf3[] = "256.356.1.1";char ip1[] = "1:1:1:2:3:4:4:8";char ip2[] = "23:43:123:89:23:89";is_ip(buf, IPV4);is_ip(buf2, IPV4);is_ip(buf3, IPV4);is_ip(ip1, IPV6);is_ip(ip2, IPV6);return 0;}

0 0
原创粉丝点击