setsockopt在KEEP_ALIVE期间发出错误 [英] setsockopt gives an error during the KEEP_ALIVE
本文介绍了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 *''
推荐答案
setsockopt
采用C样式字符串const char *
不是bool
作为第4个参数。
你可以尝试:
setsockopt
takes a C style stringconst char*
not abool
as its 4th parameter.
You could try:
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 );
查看 setsockopt()函数 [ ^ ] in MSDN和示例。第4个参数是指向存储结果的缓冲区的指针。指针的类型是const char *
,以允许不同的值类型。其他实现(POSIX)使用const void *
更清楚地表明这一点。
使用BOOL值,只需施放指针:
See the setsockopt() function[^] in the MSDN and the examples. The 4th parameter is a pointer to a buffer where the result is stored. The type of the pointer isconst char *
to allow different value types. Other implementations (POSIX) useconst void *
which indicate this more clearly.
With a BOOL value, just cast the pointer:
BOOL bOptVal = TRUE;
setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE ,(const char *)&bOptVal, sizeof(bOptVal));
这篇关于setsockopt在KEEP_ALIVE期间发出错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文