Bitcoin读取peers示例

Bitcoin读取peers示例

peers数据存储在peers.dat中,程序存储类定义如下:

/** Access to the (IP) address database (peers.dat) */
class CAddrDB
{
private:
    fs::path pathAddr;
public:
    CAddrDB();
    bool Write(const CAddrMan& addr);
    bool Read(CAddrMan& addr);
    static bool Read(CAddrMan& addr, CDataStream& ssPeers);
};

pathAddr为数据存储路径,在定义类时默认初始化:

CAddrDB::CAddrDB()
{
    pathAddr = GetDataDir() / "peers.dat";
}

即数据主目录下的peers.dat文件。

通过Read方法读取peers数据:

bool CAddrDB::Read(CAddrMan& addr)
{
    return DeserializeFileDB(pathAddr, addr);
}

CAddrMan为IP管理类,定义如下:

/** 
 * Stochastical (IP) address manager 
 */
class CAddrMan
{
......
}

通过CAddrMan的GetAddr方法来获取IP列表,定义如下:

//! Return a bunch of addresses, selected at random.
    std::vector GetAddr()
    {
        Check();
        std::vector vAddr;
        {
            LOCK(cs);
            GetAddr_(vAddr);
        }
        Check();
        return vAddr;
    }

CAddress由CService派生而来,说明如下:

/** A CService with information about it as peer */
class CAddress : public CService

CService由CNetAddr派生而来,说明如下:

/** A combination of a network address (CNetAddr) and a (TCP) port */
class CService : public CNetAddr

CNetAddr的说明如下:

/** IP address (IPv6, or IPv4 using mapped IPv6 range (::FFFF:0:0/96)) */
class CNetAddr

测试主函数如下:

int main(int argc, char** argv)
{
	/** Peers List */

	print_line(100, '=');

	std::cout<<"Peers List Test";

	print_line(100, '=');

	// 设置为测试网络 

	SelectParams(CBaseChainParams::TESTNET);

	// 设置数据存储目录 

	gArgs.SoftSetArg("-datadir","../Bitcoin");

	const CChainParams& chainparams = Params();
	// Check data path
	std::cout<<"**** Data Path: "<

示例输入:

=================================================================================================== 
Peers List Test
=================================================================================================== 
**** Data Path: "/home/lc/code/TestKey-1.5.1/../Bitcoin/testnet3"

=================================================================================================== 
0 : 172.0.0.1:18333
1 : 111.125.209.113:18333
2 : [2403:6200:8850:880:6ca0:41b4:118c:af4c]:18333
3 : 35.204.246.237:18333
4 : 61.158.149.83:18333
5 : 83.26.90.41:18335
6 : 93.78.40.92:18333
7 : 183.83.49.164:18333
8 : 61.170.130.207:18333
9 : 114.252.100.213:18333
10 : 113.47.53.198:18333
11 : [2001:16b8:20e7:bf00:1055:5e4d:e23:ecf1]:18011
12 : 113.118.234.39:18333
13 : 185.100.87.207:20001
14 : 87.21.242.204:18333
15 : 85.113.60.152:18333

===================================================================================================

源码下载地址:

https://github.com/babylco0/bitcoin_code_examples/blob/master/TestKey-1.6.0.tar.gz

你可能感兴趣的:(Bitcoin)