IP address in a variable

I'm new to C++

I want to know how i can use cin command to input a ip in a variable, i tried it a few time but didn't manage to do it, i made a little research and didn't found much, i found that i need o make the ip in a array but i don't know how to do it, i want it to be in a array bi only entering the whole ip in one cin if that's possible.
Thank you

1
2
3
4
5
6
7
8
9
#include <iostream>
using namespace std;

int main() {
	int ip;
	cout << "IP adress: ";
	cin >> ip;
	return 0;
 }
I suggest you start by getting the address as a string then validating and converting this string to an actual value. And you probably shouldn't be using a single int to try to hold this value.
How would you want to input IP? A single number? Four octets? How do you want to store it?

Assuming you want to enter octets:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <cstdint>

int main()
{
    int octets[4];
    std::uint32_t ip = 0;
    std::cout << "IP adress: ";
    for(int i = 0; i < 4; ++i) {
        if(i != 0) std::cin.get();
        std::cin >> octets[i];
        ip <<= 8u;
        ip += octets[i];
    }
    std::cout << "ip: " << ip << "\nOctets: ";
    for(int i = 0; i < 4; ++i) {
        if(i != 0) std::cout << '.';
        std::cout << +octets[i];
    }
}
IP adress: 127.0.0.1
ip: 2130706433
Octets: 127.0.0.1


@jib Actually IPv4 address is a single 32bit unsigned number. It is just separated into 4 octets for display.
Last edited on
My point was that an int is not guaranteed to be large enough to hold the value of an IP address.
std::uint32_t is guaranteed to be the correct size to hold an IPv4 address.

I don't think any compilers support a native type that can hold an IPv6 address.
Last edited on
Topic archived. No new replies allowed.