linux|linux 判断是否是合法ip,根据域名获取ip

// // Created by darren on 18-1-31. //#include #include #include #include #include #include bool isValidIP(const char *ipstr); int get_ip_by_domain(const char *domain, char *ip); void test_Big_endian(); int is_valid_ip(const char *ip_str); int main(int argc, char *argv[]) {printf("isValidIP():%d\n", isValidIP(argv[1])); printf("is_valid_ip:%d\n", is_valid_ip(argv[1])); char tmp[256]; int ret = get_ip_by_domain(argv[1], tmp); printf("domain:%d,%s\n", ret, tmp); test_Big_endian(); return 0; }int is_valid_ip(const char *ip_str) { struct sockaddr_in sa; int result = inet_pton(AF_INET, ip_str, &(sa.sin_addr)); if (result == 0) { return result; } return 1; }void test_Big_endian() { unsigned long a = 0x12345678; unsigned char *p = (unsigned char *) (&a); printf("主机字节序:%0x%0x%0x%0x\n", p[0], p[1], p[2], p[3]); unsigned long b = htonl(a); //将主机字节序转化成了网络字节序 p = (unsigned char *) (&b); printf("网络字节序:%0x%0x%0x%0x\n", p[0], p[1], p[2], p[3]); }//根据域名获取ip int get_ip_by_domain(const char *domain, char *ip) { char **pptr; struct hostent *hptr; hptr = gethostbyname(domain); if (NULL == hptr) { printf("gethostbyname error for host:%s/n", domain); return -1; } for (pptr = hptr->h_addr_list; *pptr != NULL; pptr++) { if (NULL != inet_ntop(hptr->h_addrtype, *pptr, ip, INET_ADDRSTRLEN)) { return 0; // 只获取第一个 ip } } return -1; }// ip 合法性 bool isValidIP(const char *ipstr) { if (!ipstr) return false; int a, b, c, d; int tmp = sscanf(ipstr, "%d.%d.%d.%d", &a, &b, &c, &d); printf("tmp:%d\n", tmp); if (4 != tmp) return false; printf("inet_addr:%d,%d,%d,%d,%d\n", inet_addr(ipstr), a, b, c, d); if (!(0 > a || 255 < a || 0 > b || 255 < b || 0 > c || 255 < c || 0 > d || 255 < d) && INADDR_NONE != inet_addr(ipstr)) { return true; } return false; }

    推荐阅读