我已经编写了以下代码,以实现服务器UDP,C ++在Linux中工作,这是获取错误的相对部分:
#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*)’
有什么不对,我不明白。
答案 0 :(得分:1)
添加缺少的buffer
参数后,问题出现在第五个参数:
(struct sockaddr_in*)&remaddr
它需要struct sockaddr *
:
recvfrom(welcomeSocket,buffer,1024,0,(struct sockaddr *)&remaddr,(socklen_t *)&addrlen);