-1

I am trying to write a port scanner in Go, i am facing few problems since i am new to this. Below is the code i have written till now.

package main

import (
    "fmt"
    "log"
    "net"
    "os"
)

func main() {

    callme()

}

func callme() {

    var status string
    getip := os.Args[1]
    getport := 0
    for i := 0; i < 10; i++ {
        getport += i

        data := getip + ":" + getport
        conn, err := net.Dial("tcp", data)
        if err != nil {
            log.Println("Connection error:", err)
            status = "Unreachable"
        } else {

            status = getport + " - " + "Open"
            defer conn.Close()
        }

        fmt.Println(status)

    }
}

I take ip from user as a command line arg, and then want to scan all ports on this ip. Since the net.Dial function needs data in a format like "ip:port" i am kinda confused how to concat string and int each time. Can any1 help me achieve this ?

JimB
  • 104,193
  • 13
  • 262
  • 255
StackB00m
  • 502
  • 1
  • 5
  • 16
  • 1
    If you're having trouble converting an integer to a string take a look at Go's package https://golang.org/pkg/strconv/ specifically the Itoa method – reticentroot Nov 16 '16 at 20:00
  • i tried converting int to string, then the numbers changed their values to some special chars its weird – StackB00m Nov 16 '16 at 20:02
  • That sounds like and encoding issue. – reticentroot Nov 16 '16 at 20:03
  • yea any idea how to get rid of that ? – StackB00m Nov 16 '16 at 20:03
  • 2
    Related / possible duplicate of (regarding your problem): [Golang: format a string without printing?](http://stackoverflow.com/questions/11123865/golang-format-a-string-without-printing/31742265#31742265) – icza Nov 16 '16 at 20:26

1 Answers1

9

One possibility is using strconv.Itoa(getport) to convert the int into a string. Another possibility is formatting the string, as in fmt.Sprintf("%s:%d", getip, getport) or fmt.Sprintf("%d - Open", getport).

ale64bit
  • 6,232
  • 3
  • 24
  • 44
  • Can you try these and complete the above code, so that when an ip is given it checks for each port and gives response recursively , please thanks – StackB00m Nov 16 '16 at 20:06