# GetPeersでInfoHashに対応するPeerを探す

* **GetPeersでPeerを探す**
* **AnnouncePeerでP2Pネットワーク上に値を保存する**

前章でP2Pネットワークを作成する事ができました。本章では、作成したP2Pネットワークにデータを記録する方法について解説していきます。

## GetPeerでネットワークとFindNodeはほとんど同じ。

MainLine DHT ではGetPeersメッセージを利用して、データを所持しているPeerを探します。

GetPeerコマンドは「指定してKIDに対応するデータを所持しているPeerを知っていれば、そのPeerについて教えてもらう」、もしも知っていなければ、もっとも近いPeerを教えてもらう。といった事をします。

この操作を何度も繰り返す事で、KIDともっとも近くにあるNodeを発見する事ができます。

これは、ほとんど、FinddNodesと同じような動作ですね。

* KIDの近いPeerを紹介してもらうのが同じ
* なんども、送信と受信を繰り返すのが同じ

実装もほとんど同じになります。

## AnnouncePeerでデータを記録する

GetPeerを繰り返して、上位K個のNodeが固定されたら、AnnounePeerメッセージを利用してデータを記録してもらいます。

K個のNodeへデータの記録を依頼します。複数のPeerへ依頼することによって、堅牢性が高まります。

* 発見されやすくなる
* 登録したPeerが離脱しても大丈夫
* 登録したPeerの負荷を分散することができる。

## メッセージの構成

```
arguments:  
{
  "t":"aa",
  "y":"q",
  "q":"get_peers", 
  "a": {
    "id" : "<querying nodes id>", 
    "info_hash" : "<20-byte infohash of target torrent>"
  }
}

response: have value
{
  "id" : "<queried nodes id>",
  "token" :"<opaque write token>",
  "values" : 
  ["<peer 1 info string>", "<peer 2 info string>"]
}

response: have node info
{
 "t":"aa",
 "y":"r",
 "r": {
  "id" : "<queried nodes id>",
  "token" :"<opaque write token>",
  "nodes" : "<compact node info>"
  }
}
```

FindNodeとほとんど同じですね。本書では"token"と"values"が初めて出てきました。

"token" は、レスポンスを返す側に自由に決めることができるバイトデータです。AnnouncePeerクエリを送信する時に使います。このバイトデータのサイズもレスポンスを返す側のクライアントによって、異なります。

"value" は、6バイトのデータ\[ ,]をList形式で、複数個格納しています。

ref <http://www.bittorrent.org/beps/bep_0005.html>

## 実装について

findNodeで解説したとおりです。findNodeを実装したノウハウでそのままgetPeersも実装できると思います。 なので、特別、解説するページをさかないようにしました。

Kyorohiro work

<http://kyorohiro.strikingly.com>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://nazenani-torrent.firefirestyle.net/dht/getpeers.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
