C ++ UDP bind()始终返回-1

时间:2017-07-18 23:54:22

标签: c++ sockets udp bind

我想发送一个UDP数据包。

我正在使用Visual Studio C++ 2017,我已经链接了lib Ws2_32.Lib

这是说明此问题所需的示例代码:

#include <iostream>
#include <winsock2.h>
#include <sys/types.h>
#include <memory.h>
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#include <ws2tcpip.h>


int main()
{
    sockaddr_in serverAddress;
    memset(&serverAddress, 0, sizeof(serverAddress));
    serverAddress.sin_family = AF_INET;// AF_UNSPEC;
    serverAddress.sin_addr.s_addr = INADDR_ANY;
    serverAddress.sin_port = htons(20000);

    int result = 0;
    SOCKET sock = socket(AF_INET, SOCK_DGRAM, 0); //socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);

    result = bind(sock, (sockaddr*)&serverAddress, sizeof(serverAddress));
    if (result == -1)
    {
        std::cout << "error!!!!!! Why?";
    }
}

为什么我不能bind()这里只是socket

我在这里发过this帖子,但这对我没有帮助,因为这只是一个括号问题。

2 个答案:

答案 0 :(得分:3)

您必须在WinSock的开头调用 WSAStartup()

WSADATA data;
::WSAStartup(MAKEWORD(2, 0), &data);

最后你必须打电话给 WSACleanup()

::WSACleanup();

但在继续之前,请考虑IPV6。 sockaddr_in 仅适用于IPV4。

答案 1 :(得分:-1)

这就是答案。我没有正确创建套接字。

//init
int server_length;
int port = 20000;
const int STRLEN = 256;
char recMessage[STRLEN];
char sendMessage[STRLEN];
char *sendMes = "SERVER READY";
WSADATA wsaData;
SOCKET mySocket;
SOCKET myBackup;
SOCKET acceptSocket;
sockaddr_in myAddress;

//create socket
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != NO_ERROR)
{
    cerr << "Socket Initialization: Error with WSAStartup\n";
    system("pause");
    WSACleanup();
    exit(10);
}

mySocket = socket(AF_INET, SOCK_DGRAM, 0);
if (mySocket == INVALID_SOCKET)
{
    cerr << "Socket Initialization: Error creating socket" << endl;
    system("pause");
    WSACleanup();
    exit(11);
}

myBackup = mySocket;

//bind
myAddress.sin_family = AF_INET;
myAddress.sin_addr.s_addr = inet_addr("127.0.0.1");
myAddress.sin_port = htons(port);

if (bind(mySocket, (SOCKADDR*)&myAddress, sizeof(myAddress)) == SOCKET_ERROR)
{
    cerr << "ServerSocket: Failed to connect\n";
}