windows下C++网络编程,发送组播报文,sendto()函数发送失败,WSAGetLastError()返回错误码为5

1:windows下C++网络编程,发送组播报文,sendto()函数发送失败,WSAGetLastError()返回错误码为5

2:代码如下:
// WinsockServer_1.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include
#include
#include

const int MAX_BUF_LEN = 10;
// Link with ws2_32.lib
#pragma comment(lib, "Ws2_32.lib")

int _tmain(int argc, _TCHAR* argv[])
{
WORD wVersionRequested;
WSADATA wsaData;
int err;

// 启动socket api
wVersionRequested = MAKEWORD(2, 2);
err = WSAStartup(wVersionRequested, &wsaData);
if (err != 0)
{
    return -1;
}

if (LOBYTE(wsaData.wVersion) != 2 ||
    HIBYTE(wsaData.wVersion) != 2)
{
    WSACleanup();
    return -1;
}

// 创建socket
SOCKET connect_socket;
connect_socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (INVALID_SOCKET == connect_socket)
{
    err = WSAGetLastError();
    printf("error! error code is %d/n", err);
    return -1;
}

SOCKADDR_IN sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(3779);
//sin.sin_addr.s_addr = INADDR_BROADCAST;
sin.sin_addr.s_addr = inet_addr("224.0.0.22");//设置广播地址,window下用这种形式方可

bool bOpt = true;
//设置该套接字为广播类型
if (setsockopt(connect_socket, SOL_SOCKET, SO_BROADCAST, (char*)&bOpt, sizeof(bOpt)) == SOCKET_ERROR) {
    printf("setsockopt error");
    return -1;
}

if (setsockopt(connect_socket, SOL_SOCKET, SO_DEBUG, (char*)&bOpt, sizeof(bOpt)) == SOCKET_ERROR) {
    printf("setsockopt error");
    return -1;
}

setsockopt(connect_socket, SOL_SOCKET, SO_BROADCAST, (char*)&bOpt, sizeof(bOpt));
int nAddrLen = sizeof(SOCKADDR);

char buff[MAX_BUF_LEN] = "";
while (1)
{
    sprintf_s(buff, "%s","ss");

    // 发送数据
    int nSendSize = sendto(connect_socket, buff, strlen(buff), 0, (SOCKADDR*)&sin, nAddrLen);
    if (SOCKET_ERROR == nSendSize)
    {
        err = WSAGetLastError();
        printf("error!, error code is %d/n", err);
        return -1;
    }
    printf("Send: %s/n", buff);
    Sleep(500);
}
return 0;

}

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐