'Port scanner using net.DialTimeout always manages to connect even when ports are closed

---UPDATE I send the code to a friend who then tested it on his pc. The output was as it's supposed to be. This means the issue is not code related but something else with my pc.

I am trying to make a function that scans certain ports on IP-addresses that are registered in my database. The output I get:

192.168.166.13 responding on port: 80
192.168.166.132 responding on port: 80
192.168.166.134 responding on port: 80
192.168.166.14 responding on port: 80
192.168.166.17 responding on port: 80
192.168.166.67 responding on port: 80

This is incorrect as only .13 has port 80 opened. The expected output is as follows:

192.168.166.13 responding on port: 80
192.168.166.132 not responding
192.168.166.134 not responding
192.168.166.14 not responding
192.168.166.17 not responding
192.168.166.67 not responding

My code looks like this (I call this function in the main):

func pingHosts() {

    db := sqlConnect()
    defer db.Close()
    hosts := sqlGetHostAdresses(db)
    fmt.Println(hosts)
    timeout := time.Duration(1 * time.Second)
    port := 80

    for i := 0; i < len(hosts); i++ {
        conn, err := net.DialTimeout("tcp", net.JoinHostPort(hosts[i], strconv.Itoa(port)), timeout)
        if err != nil {
            fmt.Printf("%s %s %s\n", hosts[i], "not responding", err.Error())
        }
        if conn != nil {
            fmt.Printf("%s %s %s\n", hosts[i], "responding on port:", strconv.Itoa(port))
            conn.Close()
        }
    }

hosts is the slice containing the IP-addresses. I believe the hosts slice to be correct:

[192.168.166.13 192.168.166.132 192.168.166.134 192.168.166.14 192.168.166.17 192.168.166.67]

To my knowledge the program should return an error while trying to connect to all but one address.

---Edit 1 I added the conn.Close() line if conn is not nil. This didn't change the output when using port 80. I then tried running the program to check on port 1245. The resulting output was this:

192.168.166.13 not responding dial tcp 192.168.166.13:1245: i/o timeout
192.168.166.132 not responding dial tcp 192.168.166.132:1245: i/o timeout
192.168.166.134 not responding dial tcp 192.168.166.134:1245: i/o timeout
192.168.166.14 not responding dial tcp 192.168.166.14:1245: i/o timeout
192.168.166.17 not responding dial tcp 192.168.166.17:1245: i/o timeout
192.168.166.67 not responding dial tcp 192.168.166.67:1245: i/o timeout
go


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source