Search code examples
c++ipipv4

Data type error with strings when generating random ipv4 addresses


So, i’m trying to create a loop that generates random ipv4 addresses and it works well except that i’m trying to skip the localhost loopback address "127.0.0.1". I’m assuming it’s a problem with comparing 2 different data types in if (Output == "127.0.0.1") {. Data types are my weakest point in programming and I’ve tried many different ways to fix it but to no avail. This is the code so far:

#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <cstdlib>
#include <ctime>
#define num 100
using namespace std;

void ipv4(string& createdAddress)
{
  int count = 0;
  time_t t;
  time(&t);
  srand(t);
  ostringstream Output;
  while(count < num) {
      for(int i = 0; i < 3; i++) {
        Output <<  rand() % 256;
        Output <<  ".";
      };
      Output <<  rand() % 256;
      Output << endl;
      if (Output == "127.0.0.1") {
        continue;
      } else {
        count++;
      }
    };
    createdAddress += Output.str();
};

int main()
{
  string createdAddress = "";
  ipv4(createdAddress);
  cout << createdAddress << endl;
  return 0;
};

This is the error code I’m getting:

   17 |   ostringstream 127.0.0.1;
      |                 ^~~~~~~~~
prog.cc: In function 'void ipv4(std::string&)':
prog.cc:17:17: error: expected unqualified-id before numeric constant
prog.cc:28:18: error: no match for 'operator==' (operand types are 'std::ostringstream' {aka 'std::__cxx11::basic_ostringstream<char>'} and 'const char [10]')
   28 |       if (Output == "127.0.0.1") {
      |           ~~~~~~ ^~ ~~~~~~~~~~~
      |           |         |
      |           |         const char [10]
      |           std::ostringstream {aka std::__cxx11::basic_ostringstream<char>}

Also, i’m a beginner in c++, please criticise the code if it’s bad, thanks.


Solution

  • You probably want to compare Output.str()

    As a side note, any address starting with 127. is localhost, so you probably want to filter all of them; and possibly various others, like multicast