Welcome to collectivesolver - Programming & Software Q&A. A website you can trust. All programs tested and works. Contact: aviboots(AT)netvision.net.il
Hostgator 1 Penny

BlueHost Web Hosting

Ecommerce Software - Best Ecommerce Platform Made for You - Free Trial

Ecommerce Software - Best Ecommerce Platform Made for You - Free Trial

getflywheel wordpress hosting


Distribute your Resume to 500+ Job Boards & Recruiters


7,621 questions

10,674 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 by avibootz
...