本文介绍了setsockopt在KEEP_ALIVE期间发出错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include "stdafx.h"
#include <stdio.h>
#include <windows.h>

int _tmain(int argc, _TCHAR* argv[])
{
    WSADATA wsaData = {0};
    int nResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
    SOCKET sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    BOOL bOptVal = TRUE;
    setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE , &bOptVal, sizeof(bOptVal));
    return 0;
}







它给出了一个错误



错误C2664:''setsockopt'':无法将参数4从''BOOL *''转换为''const char *''




Its gives an error

error C2664: ''setsockopt'' : cannot convert parameter 4 from ''BOOL *'' to ''const char *''

推荐答案

const char* Optval = "true";
setsockopt( sock, SOL_SOCKET, SO_KEEPALIVE, Optval, strlen( Optval ) );





这可能会编译但是会工作?这取决于与 SO_KEEPALIVE 相关联的潜在参数值。根据 [] C样式字符串实际上是一个伪装的整数,所以代码应该是





That will likely compile but will it work? That depends on the potential parameter values associated with SO_KEEPALIVE. According to this[^] the C style string is really a disguised integer so the code should be

int iOptval = 1;
int iOptSize = sizeof( int );
setsockopt( sock, SOL_SOCKET, SO_KEEPALIVE, reinterpret_cast< char* >( &iOptval ), iOptSize );


BOOL bOptVal = TRUE;
setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE ,(const char *)&bOptVal, sizeof(bOptVal));


这篇关于setsockopt在KEEP_ALIVE期间发出错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 23:44