gpt4 book ai didi

c++ - cpp Linux套接字编程错误与接受

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:25:58 26 4
gpt4 key购买 nike

这是我的第一个 linux 套接字程序。我正在使用服务器客户端模型。我已阅读教程并创建了服务器和客户端。但是我在服务器端代码方面遇到了问题。

我在接受行收到此错误消息“'int*' 到'socklen_t* {aka unsigned int*}' 的无效转换”。
我该如何解决这个问题?以下是服务器代码。

#include <stdio.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <string.h>
#include <netdb.h>

using namespace std;
#define MAX_SIZE 50

int main()
{
int sock_descriptor, conn_desc;
struct sockaddr_in serv_addr, client_addr;
char buff[MAX_SIZE];
sock_descriptor = socket(AF_INET, SOCK_STREAM, 0);
if(sock_descriptor < 0)
cout << "Failed creating socket" << endl;
bzero((char *)&serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(1234);

if(bind(sock_descriptor, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
cout << "Failed to bind" << endl;

listen(sock_descriptor, 5);
cout << "Waiting for connection...\n" << endl;

int size = sizeof(client_addr);
conn_desc = accept(sock_descriptor, (struct sockaddr *)&client_addr, &size);
if(conn_desc == -1)
cout << "Failed accepting connection" << endl;
else
cout << "Connected" << endl;

if(read(conn_desc, buff, sizeof(buff)-1) > 0)
cout << "Received %s" << buff << endl;
else
cout << "Failed receiving" << endl;

close(conn_desc);
close(sock_descriptor);

return 0;
}

最佳答案

替换

int size = sizeof(client_addr);

socklen_t size = sizeof(client_addr);

关于c++ - cpp Linux套接字编程错误与接受,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12623957/

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