原理:ftp协议是基于tcpip协议,用socket实现tcpip协议发送ftp指令、内容
IP地址转换函数 inet_pton是一个IP地址转换函数,可以在将点分文本的IP地址转换为二进制网络字节序”的IP地址,而且inet_pton和inet_ntop这2个函数能够处理ipv4和ipv6。 strerror: C语言错误提示函数:strerror和errno 相关头文件: string.h errno.h 函数原型: char*strerror(interrnum); errnum是错误的编号,要通过“errno”来获得 代码实现功能:socket连接ftp服务器21端口,发送登录账号密码命令,登录成功 代码:
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<errno.h> #include<sys/types.h> #include<sys/socket.h> #include<netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #define IPV4_PROTO AF_INET #define SOCKET_TYPE SOCK_STREAM #define protocol IPPROTO #define FTP_PORT 21 #define BUFF_LEN 4096 //return -1 connect failed -2 send failed -3 recv failed //usage pratise socket ftp int main(int argc, char **argv) { int sockFd = 0; int ret = 0; char buf[BUFF_LEN]={0}; struct sockaddr_in serverAddr; if(argc != 2) { return -1; } for(int i = 0; i < argc; i++) { printf("%s ", argv[i]); } printf("\n"); if( (sockFd = socket(AF_INET, SOCK_STREAM, 0)) < 0){ printf("create socket error: %s(errno: %d)\n", strerror(errno),errno); exit(0); } memset(&serverAddr, 0, sizeof(serverAddr)); serverAddr.sin_family = AF_INET; serverAddr.sin_port = htons(21); if( inet_pton(AF_INET, argv[1], &serverAddr.sin_addr) <= 0){ printf("inet_pton error for %s\n",argv[1]); return -1; } if( connect(sockFd, (struct sockaddr*)&serverAddr, sizeof(serverAddr)) < 0) { printf("connect error: %s(errno: %d)\n",strerror(errno),errno); return -1; } if((ret = recv(sockFd, buf, BUFF_LEN,0)) == -1) { perror("recv error"); return -3; } buf[ret] = '\0'; printf("Received : %s ",buf); printf("send msg to server: \n"); char user[] = "user ftpusr\r\n"; char passwd[] = "pass 123456aB\r\n"; if( send(sockFd, user, strlen(user), 0) < 0) { printf("send msg error: %s(errno: %d)\n", strerror(errno), errno); return -2; } printf("send : %s\n",user); if((ret = recv(sockFd, buf, BUFF_LEN,0)) == -1) { perror("recv error"); return -3; } buf[ret] = '\0'; printf("Received : %s ",buf); if( send(sockFd, passwd, strlen(passwd), 0) < 0) { printf("send msg error: %s(errno: %d)\n", strerror(errno), errno); return -2; } printf("send : %s\n",passwd); if((ret = recv(sockFd, buf, BUFF_LEN,0)) == -1) { perror("recv error"); return -3; } buf[ret] = '\0'; printf("Received : %s ",buf); close(sockFd); return 0; }
标签:ftp,socket,errno,serverAddr,服务器,include,define From: https://www.cnblogs.com/cppdevellog/p/17771047.html