客户端登陆ftp服务器
流程
- 与ftp服务器建立连接
- 发送用户名和密码
- 使服务器进入被动模式
代码实现
#include <stdio.h>
#include <stdlib.h>
#include <winsock2.h>
int cmd_send(SOCKET sock, char *cmd)
{
char readbuf[512];
int i = 0, ret;
send(sock, cmd, strlen(cmd), 0);
while(1)
{
recv(sock, &readbuf[i], 1, 0);
if(readbuf[i] == '\n')
{
readbuf[++i] = '\0';
break;
}
i++;
}
sscanf(readbuf, "%d", &ret);
printf("%s", readbuf);
return ret;
}
SOCKET login_ftp(char *user, char *pwd, char *server_ip)
{
char cmd[512] = {0};
char readbuf[512] = {0};
SOCKET sock_client = socket(PF_INET, SOCK_STREAM, 0);
struct sockaddr_in server_addr;
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(21);
server_addr.sin_addr.s_addr = inet_addr(server_ip);
if(connect(sock_client, (SOCKADDR *)&server_addr, sizeof(server_addr)) < 0)
{
printf("connect error\n");
return 0;
}
recv(sock_client, readbuf, sizeof(readbuf), 0);
printf("%s", readbuf);
sprintf(cmd, "USER %s\r\n", user);
cmd_send(sock_client, cmd);
sprintf(cmd, "PASS %s\r\n", pwd);
cmd_send(sock_client, cmd);
return sock_client;
}
int main()
{
WSADATA wsaData;
WSAStartup(MAKEWORD(2, 2), &wsaData);
char user[255], pwd[255], server_ip[255];
SOCKET sock_client;
printf("welcom to ftp_client\n");
printf("input ip: ");
scanf("%s", server_ip);
printf("input user: ");
scanf("%s", user);
printf("input password: ");
scanf("%s", pwd);
sock_client = login_ftp(user, pwd, server_ip);
closesocket(sock_client);
WSACleanup();
return 0;
}
简单代码解释
cmd_send函数用来发送命令并返回响应码,打印ftp服务器返回的信息
login_ftp函数来登陆服务器并返回socket
USER指令用来输入用户名(anonymous用户名为匿名登陆)
PASS指令用来输入密码
strlen(cmd)那行画重点。。好像不能多传,传了会出错,有多少传多少,具体原因未知
一个星期了!!第七篇~~哎太困了写不下了今天
我看见你,却试图不去看你。你来到我面前,我却闭上眼睛。——保罗·乔尔达诺
给我点十个赞我就买杯可乐庆祝下