/**//****************************************** 程序名称:socketopt.cpp 程序功能:该程序演示了getsockopt()函数和setsockopt()函数用法
changshoumeng */
#include <winsock2.h> #include <stdio.h> #include <stdlib.h> #pragma comment(lib,"ws2_32.lib") void main() { WSADATA wsaData; SOCKET s; int optname;//存放选项的值 int optlen;//选项的长度
if(WSAStartup(MAKEWORD(2,2),&wsaData) !=0) { printf("Failed to load winsock. \n"); return; } s = socket(AF_INET,SOCK_STREAM,0);//创建一个套接口 if(s == INVALID_SOCKET) { printf("socket() Error \n"); return; }
optlen = sizeof(optname); printf("---------------------------\n"); //获得套接口类型 if(getsockopt(s,SOL_SOCKET,SO_TYPE,(char *)&optname,&optlen) ==SOCKET_ERROR) { printf("getsockopt() Error: %u \n",WSAGetLastError()); return; } printf("以下信息是由getsockopt()函数取得的SO_SOCKET 级别选项实例\n"); switch(optname) { case SOCK_STREAM: printf("SO_TYPE:SOCK_STREAM \n");break; case SOCK_DGRAM : printf("SO_TYPE:SOCK_DGRAM \n");break; case SOCK_RAW : printf("SO_TYPE:SOCK_RAW \n");break; } //获取接收缓冲区的大小 if(getsockopt(s,SOL_SOCKET,SO_RCVBUF,(char *)&optname,&optlen) ==SOCKET_ERROR) { printf("getsockopt() Error: %u \n",WSAGetLastError()); return; } printf("SO_RCVBUF:%d \n",optname);
//获取发送缓冲区的大小 if(getsockopt(s,SOL_SOCKET,SO_SNDBUF,(char *)&optname,&optlen) ==SOCKET_ERROR) { printf("getsockopt() Error: %u \n",WSAGetLastError()); return; } printf("SO_SNDBUF:%d \n",optname);
optname = 16*1024; //重新设置缓冲区的大小 if(setsockopt(s,SOL_SOCKET,SO_RCVBUF,(char *)&optname,sizeof(optname) )== SOCKET_ERROR) { printf("setsockopt() Error: %u \n",WSAGetLastError()); return; } //获取重新设置的接收缓冲区的大小 if(getsockopt(s,SOL_SOCKET,SO_RCVBUF,(char *)&optname,&optlen) == SOCKET_ERROR) { printf("getsockopt() Error: %u \n",WSAGetLastError()); return; } printf("---------------------\n"); printf("使用setsockopt()函数设置后再取得的SO_RCVBUF数值\n"); printf("SO_RCVBUF:%d \n",optname); printf("---------------------\n"); WSACleanup();
}
|