Enter a IP address #107
Answered by palonza
workshop748 asked this question in Q&A
-
| Hey I'm a fairly new programming in c++. I was just curious if there a way to enter a ip address in c++ to help calculate a subnet |
Beta Was this translation helpful? Give feedback.
Answered by palonza May 28, 2023
Replies: 1 comment 4 replies
-
| hi @workshop748, in this example, 'calculateSubnetMask' takes prefix length as input and generates the corresponding subnet mask using bitwise operations and main function prompts the user to enter IP and prefix... is basic but is working... please let me know if work to you... regards #include <iostream> #include <string> #include <sstream> #include <bitset> // Function to calculate the subnet mask based on the prefix length std::string calculateSubnetMask(int prefixLength) { std::bitset<32> bits; for (int i = 0; i < prefixLength; ++i) { bits.set(i, true); } std::stringstream ss; ss << (bits.to_ulong() >> 24) << '.' << ((bits.to_ulong() >> 16) & 255) << '.' << ((bits.to_ulong() >> 8) & 255) << '.' << (bits.to_ulong() & 255); return ss.str(); } int main() { std::string ipAddress; int prefixLength; // Read IP address and prefix length from the user std::cout << "Enter IP address (e.g., 192.168.0.1): "; std::cin >> ipAddress; std::cout << "Enter prefix length (e.g., 24): "; std::cin >> prefixLength; // Calculate subnet mask std::string subnetMask = calculateSubnetMask(prefixLength); // Print the calculated subnet mask std::cout << "Subnet Mask: " << subnetMask << std::endl; return 0; } |
Beta Was this translation helpful? Give feedback.
4 replies
Answer selected by ThusharaX
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
hi @workshop748,
in this example, 'calculateSubnetMask' takes prefix length as input and generates the corresponding subnet mask using bitwise operations and main function prompts the user to enter IP and prefix... is basic but is working... please let me know if work to you... regards