我编写了以下代码,以实现在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);