Go語言簡單實現FTP協議.

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
package ftpimport ("errors""fmt""io""net""os""strconv""strings")type Ftp struct {con net.Connip  string}func NewFtp(ip string) (*Ftp, error) {buf := make([]byte, 1024)con, err := net.Dial("tcp", ip)if err != nil {return nil, err}n, err := con.Read(buf)if err != nil {return nil, err}fmt.Println(string(buf[:n]))return &Ftp{con, ip}, nil}func (self *Ftp) Login(user, pass string) error {buf := make([]byte, 1024)self.con.Write([]byte(fmt.Sprintf("USER %s\r\n", user)))self.con.Read(buf)self.con.Write([]byte(fmt.Sprintf("PASS %s\r\n", pass)))n, err := self.con.Read(buf)if err != nil {return err}if !strings.Contains(string(buf[:n]), "230 Logged on") {return errors.New(strings.TrimSpace(string(buf)))}return nil}func (self *Ftp) PutPasv(Pathname string) error {con, err := self.connection("STOR", Pathname)if err != nil {return err}File, err := os.Open(Pathname)if err != nil {con.Close()return err}io.Copy(con, File)File.Close()con.Close()buf := make([]byte, 1024)_, err = self.con.Read(buf)if err != nil {return err}return nil}func (self *Ftp) GetFile(Pathname string) error {con, err := self.connection("RETR", Pathname)if err != nil {return err}File, err := os.Create(Pathname)if err != nil {con.Close()return err}io.Copy(File, con)File.Close()con.Close()buf := make([]byte, 1024)_, err = self.con.Read(buf)if err != nil {return err}return nil}func (self *Ftp) connection(status, Pathname string) (net.Conn, error) {buf := make([]byte, 1024)self.con.Write([]byte("PASV \r\n"))n, err := self.con.Read(buf)if err != nil {return nil, err}if s := string(buf[:n]); !strings.Contains(s, "227 Entering Passive Mode") {return nil, errors.New(s)}port := getport(buf[27 : n-3])con, err := net.Dial("tcp", fmt.Sprintf("%s:%d", strings.Split(self.ip, ":")[0], port))if err != nil {return nil, err}self.con.Write([]byte(fmt.Sprintf("%s %s\r\n", status, Pathname)))n, err = self.con.Read(buf)if err != nil {con.Close()return nil, err}if !strings.Contains(string(buf[:n]), "150 Opening data channel") {con.Close()return nil, errors.New("create data link error.")}return con, nil}func getport(by []byte) int {s := string(by)list := strings.Split(s, ",")n1, err := strconv.Atoi(list[len(list)-2])if err != nil {return 0}n2, err := strconv.Atoi(list[len(list)-1])if err != nil {return 0}return n1*256 + n2}

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.