README.md 1.86 KB
Newer Older
1
# The libp2p 'host'
2

3
4
5
6
For most applications, the host is the basic building block you'll need to get started. This guide will show how to construct and use a simple host.

The host is an abstraction that manages services on top of a swarm. It provides a clean interface to connect to a service on a given remote peer.

7
If you want to create a host with a default configuration, you can do the following:
8
9
10

```go
import (
11
	"context"
12
	"crypto/rand"
13
	"fmt"
14

15
	libp2p "github.com/libp2p/go-libp2p"
16
	crypto "github.com/libp2p/go-libp2p-crypto"
17
18
)

19

20
21
22
23
24
25
// The context governs the lifetime of the libp2p node
ctx, cancel := context.WithCancel(context.Background())
defer cancel()

// To construct a simple host with all the default settings, just use `New`
h, err := libp2p.New(ctx)
26
27
28
29
if err != nil {
	panic(err)
}

30
fmt.Printf("Hello World, my hosts ID is %s\n", h.ID())
31
32
```

33
If you want more control over the configuration, you can specify some options to the constructor. In this snippet we generate our own ID and specified on which address we want to listen:
34

35
```go
36
37
// Set your own keypair
priv, _, err := crypto.GenerateEd25519Key(rand.Reader)
38
39
40
41
if err != nil {
	panic(err)
}

42
43
44
h2, err := libp2p.New(ctx,
	// Use your own created keypair
	libp2p.Identity(priv),
45

46
47
48
	// Set your own listen address
	// The config takes an array of addresses, specify as many as you want.
	libp2p.ListenAddrStrings("/ip4/0.0.0.0/tcp/9000"),
49
50
51
52
53
)
if err != nil {
	panic(err)
}

54
fmt.Printf("Hello World, my second hosts ID is %s\n", h2.ID())
55
56
```

57
And thats it, you have a libp2p host and you're ready to start doing some awesome p2p networking!
58

59
In future guides we will go over ways to use hosts, configure them differently (hint: there are a huge number of ways to set these up), and interesting ways to apply this technology to various applications you might want to build.
60

61
To see this code all put together, take a look at [host.go](host.go).