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,987 questions

51,931 answers

573 users

How to check if a string is IPv4 or IPv6 or invalid in C++

1 Answer

0 votes
#include <iostream>
#include <string>
#include <arpa/inet.h>   // inet_pton

std::string check_ip_address(const std::string& s) {
    sockaddr_in sa4{};
    sockaddr_in6 sa6{};

    // IPv4
    if (inet_pton(AF_INET, s.c_str(), &(sa4.sin_addr)) == 1) {
        return "IPv4";
    }

    // IPv6
    if (inet_pton(AF_INET6, s.c_str(), &(sa6.sin6_addr)) == 1) {
        return "IPv6";
    }

    return "Invalid";
}

int main() {
    std::cout << check_ip_address("112.128.1.2") << "\n";
    std::cout << check_ip_address("2001:0dc7:85b2:0000:0000:6d3e:0380:8651") << "\n";
    std::cout << check_ip_address("999.999.999.999") << "\n";
    std::cout << check_ip_address("abc") << "\n";
}


/*
run:

IPv4
IPv6
Invalid
Invalid

*/

 



answered Jan 19 by avibootz
...