【问题标题】:Error while creating socket in C (Visual Studio 2017)在 C 中创建套接字时出错 (Visual Studio 2017)
【发布时间】:2019-06-17 20:55:46
【问题描述】:

我正在尝试做一个客户端/服务器作业。我使用 Visual Studio 2017 并且已经更改了我可以使用套接字 (Windows Socket Programming in C) 的项目设置,但现在我的控制台总是显示“创建套接字时出错 ...:没有错误”

这是我当前的代码:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <WinSock.h>

void PrintErrorExit(char *msg)
{
    perror(msg);
    exit(0);
}

int main()
{
    int randomNumber;
    int sock = 0;
    // Erzeuge das Socket - Verbindung über TCP/IP
    sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock < 0)
        PrintErrorExit("ERROR while creating Socket ... "); 


}

【问题讨论】:

    标签: c visual-studio sockets


    【解决方案1】:

    三个问题:

    • 首先,您需要先将WSAStartup() 呼叫initialize Winsock,然后才能使用socket()

    • 其次,您需要将socket() 的返回值与INVALID_SOCKET 进行比较,如文档所述。

    • 第三,perror() 不适用于 Winsock 错误,如您的示例所示。 perror() 查看 errno,Winsock 没有设置。改用WSAGetLastError()获取Winsock函数失败的错误码,然后根据需要打印出来。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-11
    • 1970-01-01
    • 1970-01-01
    • 2017-04-04
    • 1970-01-01
    • 2019-09-24
    • 2017-12-19
    • 1970-01-01
    相关资源
    最近更新 更多