Listen for FTP Messages

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)

    }

}

Show us the relevant parts of your code.

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.

Which ftp third party package are you using ?

Why don’t you take a look at the existing FTP libraries? See https://github.com/avelino/awesome-go/blob/master/README.md#networking

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.

What is the result of this method call? What does result contain?

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.

Per documentation it reads until EOF:

ReadAll reads from r until an error or EOF and returns the data it read.

So “runs out of bytes” is probably the most correct phrase.

It seems so I replaced message reading using bufio.NewReader (dont know if this is the optimal solution) and now it works fine.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.