gpt4 book ai didi

c++ - 发送数据 C++ 的 Winsock 问题

转载 作者:行者123 更新时间:2023-11-30 04:27:02 25 4
gpt4 key购买 nike

我正在尝试使用 Winsock 编写一个简单的 FTP 客户端。

我有以下代码:

using namespace std;
#include <iostream>

#include <cstring>
#include <cstdio>

#include <winsock.h>
#include <windows.h>

int main() {

const int MAX_TRIES = 10;

char * host = "localhost";
int port = 21;
char * userName = "b8_8780454";
char * pass = "test";
char * testFileSource = "C:\\Windows\\notepad.exe";

WSADATA WSAData;
SOCKADDR_IN server;
SOCKET sock;

WSAStartup(MAKEWORD(2,2), &WSAData);
sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sock == INVALID_SOCKET) {
cout<<"fail";
return -1;
}

server.sin_family = PF_INET;
server.sin_port = htons(port);
server.sin_addr = *((struct in_addr *)gethostbyname(host)->h_addr);
memset(server.sin_zero,0,8);

int errorCode = connect(sock, (LPSOCKADDR)&server, sizeof(struct sockaddr));
int tries = 0;

while (errorCode == SOCKET_ERROR) {
if (tries >= MAX_TRIES) {
cout<<"fail 2";
return -1;
}
errorCode = connect(sock, (LPSOCKADDR)&server, sizeof(struct sockaddr));
tries++;
}


char serverMsg[2048];
Sleep(1000);
cout<<"Waiting for server response..."<<endl;
int r = recv(sock,serverMsg,2048,0);
serverMsg[r] = '\0';
cout<<endl<<endl<<"Server said: "<<endl<<serverMsg<<endl<<endl;

char userB[1024] = "USER ";
strcat(userB,userName);
cout<<"Sending... "<<userB<<endl;
cout<<"sended: "<<send(sock, userB, strlen(userB), 0)<<" bytes"<<endl;
Sleep(1000);
cout<<"Waiting for server response..."<<endl;

serverMsg[0] = '\0';
recv(sock,serverMsg,2048,0); // <-- program keeps lock here
cout<<endl<<endl<<"Server said: "<<endl<<serverMsg<<endl<<endl;
getchar();
return 0;
}

我认为发送工作不正常,但它返回 >0 但在服务器端我看不到此客户端发送任何数据。我想我可能是连接设置有问题,但我一直在检查一些网站,但我无法发现错误

这是程序打印的内容:

等待服务器响应...

Server said:
220-FileZilla Server version 0.9.31 beta
220-written by Tim Kosse (Tim.Kosse@gmx.de)
220 Please visit http://sourceforge.net/projects/filezilla/


Sending... USER b8_8780454
sended: 15 bytes
Waiting for server response...


Server said:
421 Login time exceeded. Closing control connection.
by Tim Kosse (Tim.Kosse@gmx.de)
220 Please visit http://sourceforge.net/projects/filezilla/

在我的 FTP 服务器中,我看不到此客户端向服务器发送任何数据。有什么线索吗?

最佳答案

您的用户名后需要换行 (\n)。

 strcat(userB,userName);
strcat(userB,"\n");

关于c++ - 发送数据 C++ 的 Winsock 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11162063/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com