Skip to content

Commit 5e1211d

Browse files
authored
Merge pull request ipfs#17 from tarekbadrshalaan/feat/profile/randomports
randomports: give user ability to init ipfs using random port for swarm.
2 parents 0c7d4bf + 4c7c3ba commit 5e1211d

File tree

1 file changed

+30
-1
lines changed

1 file changed

+30
-1
lines changed

config/profile.go

+30-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
11
package config
22

3-
import "time"
3+
import (
4+
"fmt"
5+
"net"
6+
"time"
7+
)
48

59
// Transformer is a function which takes configuration and applies some filter to it
610
type Transformer func(c *Config) error
@@ -160,6 +164,31 @@ fetching may be degraded.
160164
return nil
161165
},
162166
},
167+
"randomports": {
168+
Description: `Use a random port number for swarm.`,
169+
170+
Transform: func(c *Config) error {
171+
port, err := getAvailablePort()
172+
if err != nil {
173+
return err
174+
}
175+
c.Addresses.Swarm = []string{
176+
fmt.Sprintf("/ip4/0.0.0.0/tcp/%d", port),
177+
fmt.Sprintf("/ip6/::/tcp/%d", port),
178+
}
179+
return nil
180+
},
181+
},
182+
}
183+
184+
func getAvailablePort() (port int, err error) {
185+
ln, err := net.Listen("tcp", "[::]:0")
186+
if err != nil {
187+
return 0, err
188+
}
189+
defer ln.Close()
190+
port = ln.Addr().(*net.TCPAddr).Port
191+
return port, nil
163192
}
164193

165194
func appendSingle(a []string, b []string) []string {

0 commit comments

Comments
 (0)