gpt4 book ai didi

c++ - setsockopt 返回 -1 : errno is set to 0

转载 作者:行者123 更新时间:2023-11-28 04:26:33 25 4
gpt4 key购买 nike

我是网络编程的新手,我重写了来自 http://beej.us/guide/bgnet/html/multi/clientserver.html#figure2A Simple Stream ServerVisual Studio 2015 中。在这里我只发布部分代码(直到 freeaddrinfo(servinfo)),因为那里已经存在问题。

// StreamServer.cpp : Defines the entry point for the console application.
#include "stdafx.h"
#include <csignal>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <cstring>
#include <errno.h>

#include <string>
#include <sys/types.h>

#include "WinSock2.h"
#include "ws2ipdef.h"
#include "WS2tcpip.h"

#define PORT "3490" // the port users will be connecting to
#define BACKLOG 10 // how many pending connections queue will hold

// get sockaddr, IPv4 or IPv6:
void* get_in_addr(struct sockaddr* sa)
{
if (sa->sa_family == AF_INET) {
return &(((struct sockaddr_in*)sa)->sin_addr);
}

return &(((struct sockaddr_in6*)sa)->sin6_addr);
}

int main()
{
WSAData wsaData;

if (WSAStartup(MAKEWORD(2, 0), &wsaData) != 0) {
std::cout << "WSAStartup failed." << std::endl;
exit(1);
}

int sockfd, new_fd; // listen on sock_fd, new connection on new_fd
struct addrinfo hints, *servinfo, *p;
struct sockaddr_storage their_addr; // connector's address information
socklen_t sin_size;
int yes = 1;
char s[INET6_ADDRSTRLEN];
int rv;

memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE; // use my IP

if ((rv = getaddrinfo(NULL, PORT, &hints, &servinfo)) == -1) {
return 1;
}

// loop through all the results and bind to the first we can
for (p = servinfo; p != NULL; p = p->ai_next) {
if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol) == -1)) {
perror("server: socket");
continue;
}

if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (char*)&yes, sizeof(yes)) == -1) {
perror("setsockopt");
exit(1);
}

if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
closesocket(sockfd);
perror("server: bind");
continue;
}
break;
}

freeaddrinfo(servinfo);

WSACleanup();
return 0;
}

setsockopt(...) 失败并将 errno 变量设置为 0。我还打印了错误,它说 No error。我不明白我做错了什么。我认为程序应该在指定端口上运行并等待,直到某个客户端将数据发送到该端口。

最佳答案

你有点混用成语。

perror 来自 Linux(或者更广泛地说,符合 POSIX 的系统)上的编程,并且会告诉您什么是 errno

但 Windows 不使用 errno!要从 Windows 套接字函数中获取错误,您需要 WSAGetLastError()。这应该会告诉您您做错了什么(在本例中,为 SO_REUSEADDR 传递了错误类型的参数)。

关于c++ - setsockopt 返回 -1 : errno is set to 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54186443/

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