mirror of
https://github.com/netbirdio/netbird.git
synced 2025-08-19 11:20:18 +02:00
Add sharedsock example (#1116)
This commit is contained in:
35
sharedsock/example/README.md
Normal file
35
sharedsock/example/README.md
Normal file
@@ -0,0 +1,35 @@
|
||||
### How to run
|
||||
|
||||
This will only work on Linux
|
||||
|
||||
1. Run netcat listening on the UDP port 51820. This is going to be our external process:
|
||||
```bash
|
||||
nc -kluvw 1 51820
|
||||
```
|
||||
|
||||
2. Build and run the example Go code:
|
||||
|
||||
```bash
|
||||
go build -o sharedsock && sudo ./sharedsock
|
||||
```
|
||||
|
||||
3. Test the logic by sending a STUN binding request
|
||||
|
||||
```bash
|
||||
STUN_PACKET="000100002112A4425454"
|
||||
echo -n $STUN_PACKET | xxd -r -p | nc -u -w 1 localhost 51820
|
||||
```
|
||||
|
||||
4. You should see a similar output of the Go program. Note that you'll see some binary output in the netcat server too. This is due to the fact that kernel copies packets to both processes.
|
||||
|
||||
```bash
|
||||
read a STUN packet of size 18 from ...
|
||||
```
|
||||
|
||||
5. Send a non-STUN packet
|
||||
|
||||
```bash
|
||||
echo -n 'hello' | nc -u -w 1 localhost 51820
|
||||
```
|
||||
|
||||
6. The Go program won't print anything.
|
56
sharedsock/example/main.go
Normal file
56
sharedsock/example/main.go
Normal file
@@ -0,0 +1,56 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/netbirdio/netbird/sharedsock"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"os"
|
||||
"os/signal"
|
||||
)
|
||||
|
||||
func main() {
|
||||
|
||||
port := 51820
|
||||
rawSock, err := sharedsock.Listen(port, sharedsock.NewIncomingSTUNFilter())
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
log.Infof("attached to to the raw socket on port %d", port)
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
// read packets
|
||||
go func() {
|
||||
buf := make([]byte, 1500)
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
log.Debugf("stopped reading from the shared socket")
|
||||
return
|
||||
default:
|
||||
size, addr, err := rawSock.ReadFrom(buf)
|
||||
if err != nil {
|
||||
log.Errorf("error while reading packet from the shared socket: %s", err)
|
||||
continue
|
||||
}
|
||||
log.Infof("read a STUN packet of size %d from %s", size, addr.String())
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
// terminate the program on ^C
|
||||
c := make(chan os.Signal, 1)
|
||||
signal.Notify(c, os.Interrupt)
|
||||
go func() {
|
||||
for range c {
|
||||
log.Infof("received ^C signal, stopping the program")
|
||||
cancel()
|
||||
err = rawSock.Close()
|
||||
if err != nil {
|
||||
log.Errorf("failed closing raw socket")
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
<-ctx.Done()
|
||||
}
|
Reference in New Issue
Block a user