For practicing some of the basic concepts I'm writing a simple port scanner. When trying to implement goroutines however, the program panics and I get a segmentation fault:
Scanning ports
{Port:139 State:Open}
{Port:135 State:Open}
{Port:136 State:Closed}
{Port:131 State:Closed}
{Port:131 State:Open}
{Port:134 State:Closed}
{Port:134 State:Open}
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x4eb26a]
goroutine 20 [running]:
main.scanPort(0x52033b, 0x3, 0x52203e, 0xf, 0x83)
/home/athos/Projects/go-tutorial/scanner.go:33 +0x1ea
created by main.main
/home/athos/Projects/go-tutorial/scanner.go:41 +0xf1
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x4eb26a]
goroutine 23 [running]:
main.scanPort(0x52033b, 0x3, 0x52203e, 0xf, 0x86)
/home/athos/Projects/go-tutorial/scanner.go:33 +0x1ea
created by main.main
/home/athos/Projects/go-tutorial/scanner.go:41 +0xf1
exit status 2
This is my code:
package main
import (
"fmt"
"net"
"strconv"
"sync"
"time"
)
var wg sync.WaitGroup
type scanResult struct {
Port int
State string
}
func scanPort(protocol, hostname string, port int) {
defer wg.Done()
result := scanResult{Port: port}
socket := hostname + ":" + strconv.Itoa(port)
conn, err := net.DialTimeout(protocol, socket, 2*time.Second)
if err != nil {
result.State = "Closed"
fmt.Printf("%+v\n", result)
}
result.State = "Open"
fmt.Printf("%+v\n", result)
// Defers: FILO data structure
defer conn.Close()
}
func main() {
fmt.Println("Scanning ports")
for i := 130; i <= 145; i++ {
wg.Add(1)
go scanPort("tcp", "192.168.200.103", i)
}
// Wait for goroutines to complete
wg.Wait()
}
Can anyone help me see what I'm doing wrong?
return
when you handle the error? Because, if an error occurs,conn
will probably benil
.conn.Close()
is called whenconn
isnil
.