1

我正在用 C++ 编写一个 Bittorrent 客户端,需要生成一个 20 字节的 Peer ID。前 8 个字符由-WW1000-代表客户端名称和版本号的字符组成。其他 12 位需要是随机数,需要在客户端每次启动时随机生成。

如何生成 12 位随机数并将其与std::string包含前 8 个字符 ( -WW1000-) 的 a 连接起来?

4

3 回答 3

5
const string CurrentClientID = "-WW1000-";  
ostringstream os;
for (int i = 0; i < 12; ++i)
{
    int digit = rand() % 10;
    os << digit;
}
string result = CurrentClientID + os.str();
于 2012-07-23T16:06:58.493 回答
2

一种方法是使用rand()N 次创建一个大字符串,其中 N 是您想要的数字的长度(一种避免模偏差的天真的方法):

size_t length = 20;
std::ostringstream o;

o << "-WW1000-";
for (size_t ii = 8; ii < length; ++ii)
{
    o << rand(); // each time you'll get at least 1 digit
}

std::string id = o.str().substr(0, length);

如果你有一个足够新的 C++ 编译器/库:

// #include <random>
std::random_device r;
std::mt19937 gen(r());
std::uniform_int_distribution<long long> idgen(0LL, 999999999999LL);

std::ostringstream o;
o << "-WW1000-";
o.fill('0');    
o.width(12);
o << idgen(gen);

std::string id = o.str();
于 2012-07-23T16:14:31.560 回答
1

我不知道您的 id 必须有多“安全”,但因为您说:

that need to be generated randomly every time the client starts,

您可能只使用该信息(1970-01-01 之后的 10 位数字)并添加另外两个随机数字(00..99):

using namespace std;
...
...
ostringstream id;
id << "-WW1000-" << setw(10) << setfill('0') << time(0) << setw(2) << rand()%100;
...

在我的系统上,这将在此刻打印:

cout << id.str() << endl;

    -WW1000-134306070741

如果您的要求更强,您当然应该使用基于完全随机的变体。

于 2012-07-23T16:27:23.653 回答