gpt4 book ai didi

c++ - 已修复 : C++ server/client program: "Connection refused"

转载 作者:行者123 更新时间:2023-11-30 19:44:03 25 4
gpt4 key购买 nike

我正在编写一个简单的程序来将文件从服务器传输到客户端(目前两者都在同一台计算机上)。使用“telnet 127.0.0.1 [端口]”,我可以成功从服务器获取文件,但是当我运行客户端时,服务器拒绝连接。我怀疑客户端正在尝试连接到错误的地址,但我不确定。如果有帮助的话,我还添加了一些 GDB 测试输出。

服务器:“./server 0 4100 bigfile 100 0.01”

int main(int argc, char* argv[]) 
{
int sockfd;
if(!(sockfd = socket(AF_INET, SOCK_STREAM, 0))) {
error("Failed to create socket");
}

struct sockaddr_in serv_addr, cl_addr;
bzero((void*) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(atoi(argv[2]));
if(bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
error("Failed to bind");
}
listen(sockfd, 10);

int fd = open(argv[3], O_RDONLY);
int bufsize = atoi(argv[4]);
int packet_period = atoi(argv[5]);
size_t cl_addr_len = sizeof(cl_addr);
char *buf = new char[bufsize];
while(true) {
int sd;
cout << "waiting for client..." << endl;
if(!(sd = accept(sockfd, (struct sockaddr *) &cl_addr, (socklen_t*) &cl_addr_len))) {
error("Failed to acccept");
}
cout << "Accepted client connection" << endl;
lseek(fd, 0, SEEK_SET);
while(int n = read(fd, buf, bufsize)) {
cout << "Transferring " << buf << endl;
usleep(100000);
write(sd, buf, n);
}
}
}

客户端:“./client 0 127.0.0.1 4100 大文件统计信息”

int main(int argc, char *argv[])
{
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
error("Failed to open socket");
}

struct sockaddr_in serv_addr;
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = inet_addr(argv[2]);
serv_addr.sin_port = htons(atoi(argv[3])); // I tried both htons and htonl
if (connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0) {
error("Failed to connect");
}

int n;
char buf[256];
int fd = open(argv[4], O_RDONLY);
while((n = read(sockfd, buf, 256)) > 0) {
printf("Received: %s\n", buf);
write(fd, buf, n);
}

close(fd);
close(sockfd);
return 0;
}

GDB 输出:

(gdb) r
Starting program: [...]/client 0 127.0.0.1 4100 bigfile stats

Breakpoint 1, main (argc=6, argv=0x7fffffffde68) at client.cpp:31
31 if (connect(sockfd,(struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {

(gdb) p serv_addr
$1 = {sin_family = 2, sin_port = 0, sin_addr = {s_addr = 16777343},
sin_zero = "\000\000\000\000\000\000\000"}

最佳答案

{sin_family = 2, sin_port = 0, sin_addr = {s_addr = 16777343}, sin_zero = "\000\000\000\000\000\000\000"}

所以 sin_port 是错误的:它不应该为零。设置它的代码是:

serv_addr.sin_port = htonl(atoi(argv[3]));

问题就出在这里。应该是

serv_addr.sin_port = htons(atoi(argv[3]));

不是今天的问题,而是

printf("Received: %s\n", buf);

应该是

printf("Received: %.*s\n", n, buf);

关于c++ - 已修复 : C++ server/client program: "Connection refused",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28820448/

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