macdylan / sm2uploader

A command-line tool for send the gcode file to Snapmaker Printers via WiFi connection.
MIT License
44 stars 4 forks source link

Broadcast address calculation was broken in 2c99a44 #11

Closed lestrrat closed 10 months ago

lestrrat commented 10 months ago

The code here breaks broadcast address calculation, as applying the mask simply yields in the right most octet as 0.

Here's a fix. Let me know if you want me to create PR for it

diff --git a/discover.go b/discover.go
index 3ecd630..78ad5e6 100644
--- a/discover.go
+++ b/discover.go
@@ -1,6 +1,7 @@
 package main

 import (
+       "encoding/binary"
        "fmt"
        "log"
        "net"
@@ -95,8 +96,15 @@ func getBroadcastAddresses() ([]string, error) {
                        continue
                }
                for _, addr := range addrs {
-                       if n, ok := addr.(*net.IPNet); ok && !n.IP.IsLoopback() && n.IP.To4() != nil {
-                               baddrs = append(baddrs, n.IP.Mask(n.IP.DefaultMask()).String())
+                       if n, ok := addr.(*net.IPNet); ok && !n.IP.IsLoopback() {
+                               if v4addr := n.IP.To4(); v4addr != nil {
+                                       // convert all parts of the masked bits to its maximum value
+                                       // by converting the address into a 32 bit integer and then
+                                       // ORing it with the inverted mask
+                                       baddr := make(net.IP, len(v4addr))
+                                       binary.BigEndian.PutUint32(baddr, binary.BigEndian.Uint32(v4addr)|^binary.BigEndian.Uint32(n.IP.DefaultMask()))
+                                       baddrs = append(baddrs, baddr.String())
+                               }
                        }
                }
        }

PS: I'd also like to create a PR that removes duplicate broadcast addrs, if it's OK with you.

macdylan commented 10 months ago

LGTM, please create a PR, thank you.

lestrrat commented 10 months ago

@macdylan done: #12