利用setsockopt设置套接字某属性的属性值

       之前学习了getsockopt, 现在自然有了setsockopt, 来看看吧:

#include 
#include 
#pragma comment(lib,"ws2_32.lib")   

int main()
{
	WSADATA wsaData;
	WSAStartup(MAKEWORD(2, 2), &wsaData);
	unsigned int serverSocket = socket(AF_INET, SOCK_STREAM, 0);


	// SO = socket option = option = opt = 选项 = 属性, 比如SO_KEEPALIVE表示心跳设置状态的属性值

	int optVal = -1;
	int optLen = sizeof(int);
	getsockopt(serverSocket, SOL_SOCKET, SO_KEEPALIVE, (char*)&optVal, &optLen);
	printf("心跳设置状态: %d\n", optVal); // 0, 没有心跳机制

	BOOL bOptVal = TRUE;
	int  bOptLen = sizeof(bOptVal);
	setsockopt(serverSocket, SOL_SOCKET, SO_KEEPALIVE, (char*)&bOptVal, bOptLen);

	getsockopt(serverSocket, SOL_SOCKET, SO_KEEPALIVE, (char*)&optVal, &optLen);
	printf("心跳设置状态: %d\n", optVal); // 1, 启动心跳机制

	WSACleanup();
	return 0;
}


你可能感兴趣的:(S1:,C/C++,s2:,软件进阶,s2:,网络编程)