gpt4 book ai didi

C++ UDP recvfrom 行为异常,WSAGetLastError = 10014

转载 作者:太空宇宙 更新时间:2023-11-04 15:45:29 27 4
gpt4 key购买 nike

我的代码在 Windows 上表现得很奇怪,但在 Linux 上工作...这是我的 server.cpp:

#include <cstdio>
#include "packet.h"
#include "socket.h"

int main(int argc, char *argv[])
{
Socket s;

s.bindAt(1337);
for (int i = 0; i < 20; i++) {
Packet p;
int32_t a;
char *b;

int abc = s.receive();
printf("abc = %d\n", abc);
printf("error = %d\n", WSAGetLastError());
p.getInt(&a);
p.getString(&b);

printf("int = %d\nstring = %s\n", a, b);
delete[] b;
}

return 0;
}

这里是 socket.cpp:

Socket::Socket()
{
#ifdef _WIN32
WSADATA wsa;
if (sockNum == 0 && WSAStartup(MAKEWORD(2, 2), &wsa) != 0)
throw 1;
#endif

sock = socket(AF_INET, SOCK_DGRAM, 0);
#ifdef _WIN32
if (sock == INVALID_SOCKET)
#else
if (sock == -1)
#endif
throw 2;

addrlen = 0;
sockNum++;
}


int Socket::bindAt(unsigned short port)
{
struct sockaddr_in sa = { 0 };
memset(&sa, 0, sizeof(sa));

sa.sin_family = AF_INET;
sa.sin_port = htons(port);
sa.sin_addr.s_addr = htonl(INADDR_ANY);
return bind(sock, (struct sockaddr *) &sa, sizeof(sa));
}

ssize_t Socket::receive()
{
ssize_t n;

#ifdef _WIN32

char msg[100];
n = recvfrom(sock,msg, sizeof(msg), 0,(SOCKADDR*) &addr, &addrlen);
#else
n = recvfrom(sock, p->buf, p->bufSize, 0,
(struct sockaddr *) &addr, &addrlen);
#endif
/*if (n < 0)
p->bufSize = 0;
else
p->bufSize = n;*/
return n;
}

基本上是标题:

typedef SOCKET socket_t;
typedef int ssize_t;

class Socket
{
public:
socket_t sock;
socklen_t addrlen;
struct sockaddr_in addr;

Socket();
~Socket();

int connect(const char *ip, unsigned short port);
int bindAt(unsigned short port);
ssize_t send(Packet *p);
ssize_t receive();
};

如果我将 recvfrom 的最后 2 个参数、(SOCKADDR*) &addr 和 &addrlen 更改为 NULL,它会起作用,但这 2 个参数有什么问题?

最佳答案

而不是这个:

addrlen = 0;

这样做:

addrlen = sizeof(sockaddr_in)

它应该可以工作,因为您正确识别了输出地址缓冲区指针的大小。

关于C++ UDP recvfrom 行为异常,WSAGetLastError = 10014,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17306405/

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