I am trying to establish a ftp connection with a server. I can start the connection and send messages but I’m having trouble listening for and reading responses. Is there a way to listen passively on an active TCPConn connection or do I need something else? package main
import (
"fmt"
"net"
"os"
)
func main() {
// Error if number of arguments doesn't match
if len(os.Args) < 2 {
fmt.Fprintf(os.Stderr, "Usage:%s host:port", os.Args[0])
os.Exit(1)
}
// The service in form of a string
//(here the ipv4 address and port number X.X.X.X:PN)
service := os.Args[1]
// Create TCPAddr from the service string
tcpAddr, err := net.ResolveTCPAddr("tcp4", service)
checkError(err)
// Create TCP connection
conn, err := net.DialTCP("tcp", nil, tcpAddr)
checkError(err)
// Send query to FTP server
_, err = conn.Write([]byte("USER admin\r\n"))
checkError(err)
// Read from the FTP server
result, err = ioutil.ReadAll(conn)
checkError(err)
// Close Connection
conn.Close()
// Print Results
fmt.Println(string(result))
os.Exit(0)
}
func checkError(err error) {
if err != nil {
fmt.Fprintf(os.Stderr, "Fatal error: %s", err.Error())
os.Exit(1)
}
}
Here it is. I can send commands and arguments to the server but ReadAll doesn’t catch the reply. I want to be able to print the replies from the server.
I’m not using a third-party package. I know there are some ftp packages on github but I’m making this program as a test for a future application for which I will have to make custom massages and using an external library kinda defeats the point.
According to the documentation it should return a []byte, but that is where the program gets stuck. Earlier I tried a program which used the HEAD http message and it worked.
My guess is that readall expects something to either run out of bytes or end with for example \0 or \n. Try reading only a few bytes and see if you do get a response at all.