Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,872 questions

51,795 answers

573 users

How to check if a string is valid IPv4 (IP) address in C++

1 Answer

0 votes
#include <iostream>

using std::cout;
using std::endl;

#define DELIMITER "."

int is_only_digits(char *ip)
{
	while (*ip) {
		if (*ip >= '0' && *ip <= '9')
			ip++;
		else
			return 0;
	}
	return 1;
}

int is_valid_IPv4(char *ip)
{
	int n, dots = 0;
	char *p;

	if (ip == NULL)
		return 0;

	p = strtok(ip, DELIMITER);
	if (p == NULL)
		return 0;

	while (p) {
		if (!is_only_digits(p))
			return 0;

		n = atoi(p);

		if (n >= 0 && n <= 255) {
			p = strtok(NULL, DELIMITER);
			if (p != NULL)
				dots++;
		}
		else
			return 0;
	}

	if (dots == 3)
		return 1;

	return 0;
}

int main()
{
	char ip1[] = "127.0.0.1";
	char ip2[] = "172.16.251.1";
	char ip3[] = "85.98.555.1";
	char ip4[] = "255.255.255.a";
	char ip5[] = "255.255.255.0.0";

	cout << ip1; is_valid_IPv4(ip1) ? cout << " Valid" << endl : cout << " Not valid" << endl;
	cout << ip2; is_valid_IPv4(ip2) ? cout << " Valid" << endl : cout << " Not valid" << endl;
	cout << ip3; is_valid_IPv4(ip3) ? cout << " Valid" << endl : cout << " Not valid" << endl;
	cout << ip4; is_valid_IPv4(ip4) ? cout << " Valid" << endl : cout << " Not valid" << endl;
	cout << ip5; is_valid_IPv4(ip5) ? cout << " Valid" << endl : cout << " Not valid" << endl;

	return 0;
}


/*
run:

127.0.0.1 Valid
172.16.251.1 Valid
85.98.555.1 Not valid
255.255.255.a Not valid
255.255.255.0.0 Not valid

*/

 



answered May 15, 2018 by avibootz

Related questions

1 answer 233 views
2 answers 212 views
1 answer 176 views
1 answer 149 views
1 answer 178 views
...