ftp.h文件
#ifndef __FTP_H_
#define __FTP_H_
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include "common.h"
int ftpcmd(int sockftp,char *fmt,...);
int ftp(char *host,char *port,char *user,char *pass,char *filename,char *savefile);
#endif
ftp.c文件
#include "ftp.h"
int verbose = 1;
FILE *ftpio = NULL;
char buf[4096];
int main(int argc,char *argv[])
{
if (argc<6)
{
dprint("usgs:%s /n",argv[0]);
exit(-1);
}
ftp(argv[1],argv[2],argv[3],argv[4],argv[5],argv[6]);
return 1;
}
int ftp(char *host,char *port,char *user,char *pass,char *filename,char *savefile)
{
int sockftp = -1,sockdata = -1,sockxfer = -1;
struct sockaddr_in addr;
unsigned long hostip;
int len,tmp,err;
int retval = -1;
int savefd;
unsigned char *c,*p;
struct hostent *he;
hostip = inet_addr(host);
if (hostip == -1)
{
he = gethostbyname(host);
if (he == NULL)
return -1;
hostip = * (unsigned long *)he->h_addr;
}
sockftp = socket(AF_INET,SOCK_STREAM,0);
if (sockftp == -1)
goto out;
addr.sin_family = PF_INET;
//addr.sin_port = htons(21);
addr.sin_port = htons(atoi(port));
addr.sin_addr.s_addr = hostip;
if (connect(sockftp,(struct sockaddr *)&addr,sizeof(addr)) == -1)
goto out;
err = ftpcmd(sockftp,NULL);
if (err != 220)
goto out;
err = ftpcmd(sockftp,"USER %s",user);
if (err != 331)
goto out;
err = ftpcmd(sockftp,"PASS %s",pass);
if (err != 230)
goto out;
err = ftpcmd(sockftp,"TYPE I");
if (err != 200)
goto out;
sockdata = socket(AF_INET,SOCK_STREAM,0);
if (sockdata == -1)
goto out;
tmp = sizeof(addr);
getsockname(sockftp,(struct sockaddr *)&addr,&tmp);
addr.sin_port = 0;
if (bind(sockdata,(struct sockaddr *)&addr,sizeof(addr)) == -1)
goto out;
if (listen(sockdata,1) == -1)
goto out;
tmp = sizeof(addr);
getsockname(sockdata,(struct sockaddr *)&addr,&tmp);
c = (unsigned char *)&addr.sin_addr;
p = (unsigned char *)&addr.sin_port;
err = ftpcmd(sockftp,"PORT %d,%d,%d,%d,%d,%d",
c[0],c[1],c[2],c[3],p[0],p[1]);
if (err != 200)
goto out;
err = ftpcmd(sockftp,"RETR %s",filename);
if (err != 150)
goto out;
tmp = sizeof(addr);
sockxfer = accept(sockdata,(struct sockaddr *)&addr,&tmp);
if (sockxfer == -1)
goto out;
savefd = open(savefile,O_WRONLY|O_CREAT,0644);
if (savefd == -1)
goto out;
retval = 0;
while ((len=read(sockxfer,buf,sizeof(buf)))>0)
{
write(savefd,buf,len);
retval += len;
};
close(savefd);
out:
close(sockxfer);
close(sockdata);
close(sockftp);
if (ftpio)
{
fclose(ftpio);
ftpio = NULL;
}
return retval;
}
int ftpcmd(int sockftp,char *fmt,...)
{
va_list vp;
int err,len;
if (ftpio == NULL)
{
ftpio = fdopen(sockftp,"r");
if (ftpio == NULL)
return -1;
}
if (fmt)
{
va_start(vp,fmt);
len = vsprintf(buf,fmt,vp);
buf[len++] = '/r';
buf[len++]='/n';
write(sockftp,buf,len);
if (verbose)
write(1,buf,len);
}
dprint("command is %s/n",fmt);
do
{
if (fgets(buf,sizeof(buf),ftpio) == NULL)
return -1;
if (verbose)
dprint(buf);
} while(buf[3] == '-');
sscanf(buf,"%d",&err);
return err;
}