2016-01-05 19:46:22|?次阅读|上传:wustguangh【已有?条评论】发表评论
关键词:C/C++, 网络通信|来源:唯设编程网
int CFTP::ftp_sendcmd( const char* p_cmd,char* buf_recv,size_t buf_length ) { int errCode = -1; //1.发送命令 save_log(p_cmd, m_pLogFile);//应该保存ftp运行日志 int ret = send(m_sockctrl,p_cmd,strlen(p_cmd),0); if(-1 == ret){ errCode = WSAGetLastError(); return -1; } //2.返回内容 memset(buf_recv,'',buf_length); int len = recv(m_sockctrl,buf_recv,buf_length,0); //接收残余数据 char tmp[1024] = {0}; while(len != SOCKET_ERROR && len != 0){ len = recv(m_sockctrl,tmp,sizeof(tmp),0); if(len != SOCKET_ERROR && len != 0){ strcat(buf_recv,tmp); memset(tmp,0,sizeof(tmp)); } } save_log(buf_recv, m_pLogFile);//应该保存ftp运行日志 return 0; }
函数接收三个参数,分别是:p_cmd:字符串表示的命令、buf_recv:接受返回内容的缓存区、buf_length:缓存区长度,同样,使用send发送命令,使用recv接收返回的内容。
int CFTP::ftp_connect(int timeout) { m_sockctrl = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); //设置超时 if (setsockopt(m_sockctrl,SOL_SOCKET,SO_RCVTIMEO, (const char*) &timeout,sizeof(timeout)) == -1) { perror("setsockopt"); closesocket(m_sockctrl); return -1; } if(0==m_sockctrl) return -1; struct sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_port = htons(21); addr.sin_addr.s_addr = inet_addr(m_ip); int err = connect(m_sockctrl,(sockaddr*)&addr,sizeof(addr)); if(err) return -1; //220 Microsoft FTP Service err = recv_buf(m_resp,sizeof(m_resp)); if(err || get_state_code(m_resp) != 220) return -1; return 0; }
通过connect函数与ftp服务器建立连接,根据返回状态码判断连接是否成功建立。