gpt4 book ai didi

c++ - 服务器 UDP 函数 recvfrom

转载 作者:太空宇宙 更新时间:2023-11-04 10:40:16 25 4
gpt4 key购买 nike

我写了下面的代码,实现了在 Linux 中工作的服务器 UDP,C++,这是出错的相关部分:

#include<iostream>
#include<arpa/inet.h>
#include<unistd.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
using namespace std;


int main()
{
int welcomeSocket,newSocket,nBytes;
struct sockaddr_in serverAddr;
struct sockaddr_in remaddr;
char buffer[1024];
socklen_t addrlen;

welcomeSocket=socket(AF_INET,SOCK_DGRAM,0);
if(welcomeSocket<0)
{
cout<<"Errr"<<endl;
}
else
{
cout<<"succes"<<endl;
serverAddr.sin_family=AF_INET;
serverAddr.sin_port=htons(7891);
serverAddr.sin_addr.s_addr=inet_addr("127.0.0.1");
if(bind(welcomeSocket,(struct sockaddr*)&serverAddr,sizeof(serverAddr))<0)
{
cout<<"bind failed"<<endl;
return 0;
}
else
{
addrlen=sizeof(remaddr);
while(1)
{
cout<<"Waiting on port 7891"<<endl;
recvfrom(welcomeSocket,buffer,1024,0,(struct sockaddr_in*)&remaddr,(socklen_t*)&addrlen);

}
}

}
}

但是当我使用 make 编译时,我得到一个关于函数 recvfrom 的错误,我遇到的错误是:

invalid conversion from ‘int’ to ‘void*’ [-fpermissive]
invalid conversion from ‘sockaddr_in*’ to ‘int’ [-fpermissive]
cannot convert ‘socklen_t* {aka unsigned int*}’ to ‘sockaddr*’ for argument ‘5’ to ‘ssize_t recvfrom(int, void*, size_t, int, sockaddr*, socklen_t*)’

怎么了,我不明白。

最佳答案

添加缺少的 buffer 参数后,问题出在第五个参数上:

(struct sockaddr_in*)&remaddr

它需要一个struct sockaddr *:

recvfrom(welcomeSocket,buffer,1024,0,(struct sockaddr *)&remaddr,(socklen_t *)&addrlen);

关于c++ - 服务器 UDP 函数 recvfrom,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35442635/

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