当前位置:网站首页>The socket option
The socket option
2022-08-01 07:27:00 【oldmao_2000】
文章目录
WinSockSeveral functions are provided to get and set socket options.Get options to get some parameters related to the socket、操作方式等;Setting options can change the parameters of the socket、Controls the behavior of the underlying protocol, etc.本章主要介绍:getsockopt/setsockopt、WSAIoctl和ioctlsocket,It also introduces the common setting options of these functions.
setsockopt
getsockopt/setsockoptOptions for getting and setting sockets, respectively,这里主要以setsockopt为例进行讲解.
https://docs.microsoft.com/en-us/windows/win32/api/winsock/nf-winsock-setsockopt
int setsockopt(
[in] SOCKET s,
[in] int level,
[in] int optname,
[in] const char *optval,
[in] int optlen
);
参数①
需要设置Socket句柄
参数②
Since options are hierarchical,Hence the naming given herelevel,i.e. to which the option belongslevel(类别)
https://docs.microsoft.com/en-us/windows/win32/winsock/socket-options
常见的level有:
(画表)
IPPROTO_IP:IPv4协议选项
IPPROTO_IPV6:IPv6协议选项
IPPROTO_RM:可靠/Stable multicast option
IPPROTO_TCP:TCP选项
IPPROTO_UDP:UDP选项
NSPROTO_IPX:IPX选项
SOL_APPLETALK:AppleTalk选项
SOL_IRLMP:Infrared connection management protocol options
SOL_SOCKET:套接字选项
The function used to set options is:setsockopt;The function used to get options is:getsockopt
Some options are not configurable,Equivalent to a read-only option.
Of course, there are also some options that can be both set and read.
参数③
The name of the option to set
参数④
The option value to set,Defined using pointers
There are two types of option values:Boolean and non-boolean values.Options for booleans,A non-zero integer can be set to flag to enable or allow this option,设置0Used to mark off or disable this option.For non-boolean options,The value or structure pointer corresponding to the option value needs to be set to the parameter④.
参数⑤
参数④的大小
返回值
成功,返回0
失败,返回SOCKET_ERROR
注意:
1.setsockopt一般应在bindcalled after the operation,否则setsockoptEven the settings are not checkedTCP/IP选项,直到调用bind后,才会检查TCP/IP选项,这种情况下,setsockoptwill only return successful execution.
2.Open handle callsetsockopt后,再调用sendto,则相当于调用bind.
3.The getting or setting of options takes into account the calling order,For example, call get when no error is reportedSO_ERRORyou won't get an error message.
IPPROTO_IP
https://docs.microsoft.com/en-us/windows/win32/winsock/ipproto-ip-socket-options
只写:
IP_ADD_MEMBERSHIP:加入多播组
IP_DROP_MEMBERSHIP:离开多播组
可读可写
IP_HDRINCL:Used to indicate whether to use customIP头,Only raw sockets are supported
IP_OPTIONS:设置IP包头中optional字段中的数据.
IP_TOS:设置IP包头中TOS字段中的数据.
IP_TTL:设置IP包头中TTL字段中的数据.
IP_DONTFRAGMENT:设置是否忽略MTU的限制,不分片,只支持UDP、ICMP.启用该选项后,Send data larger than the local interfaceMTU会失败,错误码为:WSAEMSGSIZE.
IPPROTO_TCP
TCP_NODELAY:设置是否使用Nagle算法,That is, whether the buffer only has data,不等待,立即发送.Applications that implement communications should be set to send immediately to reduce latency.
SOL_SOCKET
https://docs.microsoft.com/en-us/windows/win32/winsock/sol-socket-socket-options
只读:
SO_ACCEPTCONN:Used to see if the socket is inlisten状态.
SO_CONNECT_TIME:Used to query the elapsed time for the client to request a connection,以秒为单位.只支持TCP,Usually used to determine the connection waiting too long,and close it.
SO_PROTOCOL_INFO:Used to query the underlying protocol information,作用与WSAEnumProtocols类似.
SO_ERROR:Used to query the last timeSocketThe error code that occurred on ,and clear the error.
SO_TYPE:用于查询Socket的类型,例如:SOCK_STREAM、SOCK_DGRAM等.
SO_MAX_MSG_SIZE:Get the size of the largest datagram that can be sent at one time,Can only be used for datagram sockets.
可读可写
SO_BROADCAST:For viewing or settingSocketWhether broadcast data can be sent,只能用于IPX、UDP,不可用于TCP.on networks that do not support broadcasting(例如:点对点链路)Setting this option on has no effect.
SO_CONDITIONAL_ACCEPT:用于设置服务器Socket是否自动Accept客户端的连接请求,默认是False,服务器会自动Accept客户端的连接请求(完成三次握手),设置为True后,An application call is requiredWSAAccept(https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsaaccept)回调函数完成Accept客户端的连接请求.
SO_DONTLINGER:Setting this option causes the socket to be closed(closesocket)后,The socket still remains open,And continue to send the data that has not been sent and then close it,只支持TCP.
SO_LINGER:Continue to the next option,Sets the length of time the socket remains open,单位为秒.
SO_REUSEADDR:用于将多个Socket绑定到相同IP地址和端口号
SO_EXCLUSIVEADDRUSE:Used to set prevent multipleSocket绑定到相同IP地址和端口号,This option must be onbindThe previous setting is valid.SO_EXCLUSIVEADDRUSE设置后SO_REUSEADDR无效.
SO_KEEPALIVE:After setting, the client will every other1Seconds to send heartbeat data to the server,保持正常连接,Sending can be maintained for the longest time2hourly heartbeat data,只支持TCP.
SO_OOBINLINE:Setting this option enables out-of-band data(OOB)Treated as in-band data,Only open is supportedOOB的TCP.
SO_RCVBUF:Used to set the size of the socket receive data buffer,This data buffer isSocketBuilt-in for storing received data,不是RecvThe buffer specified in the function.(加解释)
SO_SNDBUF:同上,But what is set is the size of the send data buffer.
SO_RCVTIMEO:recvTime to wait when blocking calls,单位是毫秒,默认值为0,代表一直等待.
SO_SNDTIMEO:同上,但设置的是sendTime to wait when blocking calls.
ioctlsocket
ioctlsocketCommand and what to say belowWSAIoctl类似,The former is mainly based on Winsock 1.0版本,兼容性较好;而后者基于Winsock 2.0版本,功能更加强大,More options are supported.
https://docs.microsoft.com/zh-cn/windows/win32/api/winsock/nf-winsock-ioctlsocket
int ioctlsocket(
[in] SOCKET s,
[in] long cmd,
[in, out] u_long *argp
);
参数①
Socket句柄
参数②
操作码/命令
1.FIONBIO:这个命令将socketput in a non-blocking state.在重叠IOin the communication mode,Just execute functions that involve non-blocking commands,对应SocketIt will automatically enter the non-blocking state,不需要额外调用FIONBIO进行设置.
2.FIONREAD:返回指定SocketThe number of bytes that can be read on.也可直接调用recvDirectly receive the corresponding data.
3.SIOCATMARK:返回Socket是否有OOBData to be read,This command only applies to settingsSO_OOBINLINE的SOCK_STREAM类型Socket.
参数③
The value to be set by the opcode
返回值
成功,返回0;
失败,返回SOCKET_ERROR.
WSAIoctl
https://docs.microsoft.com/en-us/windows/win32/api/Winsock2/nf-winsock2-wsaioctl
int WSAAPI WSAIoctl(
[in] SOCKET s,
[in] DWORD dwIoControlCode,
[in] LPVOID lpvInBuffer,
[in] DWORD cbInBuffer,
[out] LPVOID lpvOutBuffer,
[in] DWORD cbOutBuffer,
[out] LPDWORD lpcbBytesReturned,
[in] LPWSAOVERLAPPED lpOverlapped,
[in] LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
);
参数①
Socket句柄
参数②
操作码/命令
https://docs.microsoft.com/en-us/windows/win32/winsock/winsock-ioctls
1.SIO_ENABLE_CIRCULAR_QUEUEING:用于设置Socket缓冲区满后,Whether to replace the buffered queue's data with new data,仅支持UDP.
2.SIO_FLUSH,清空Socket发送缓冲区.
3.SIO_GET_EXTENSION_FUNCTION_POINTER,Get the extension function pointer address,例如AcceptEx.
4.SIO_KEEPALIVE_VALS,和setsockopt函数的SO_KEEPALIVEOptions matter,This command can set oneTCPThe length of time for the connection to be disconnected after a period of inactivity,And the interval of heartbeat data.
5.SIO_RCVALL:设置SocketPort numbers are ignored,Receives all sent to the current interface IPv4 或 IPv6 数据包.This opcode requires administrator privileges,套接字类型为SOCK_RAW
6.SIO_ROUTING_INTERFACE_QUERY:Returns the interface corresponding to the destination address according to the destination addressIP地址.
7.SIO_ROUTING._INTERFACE_CHANGE:查询当前SocketThe bound network interface correspondsIP地址是否发生变化.Code that specifically handles changes can be written in the callback function.
8.SIO_ADDRESS LIST_QUERY,All interfaces of a certain protocol of the current computer can be queried.(看例子)
9.SIO_ADDRESS_LIST_CHANGE,A local protocol can be queriedIP地址是否有变化.Code that specifically handles changes can be written in the callback function.
10.
参数③
A pointer to the opcode input buffer
参数④
参数③的大小
参数⑤
A pointer to the opcode output buffer
参数⑥
参数⑤的大小
参数⑦
The actual return value size
参数⑧
Overlapping structs in async mode
参数⑨
要执行的回调函数,定义方式如下:
void CALLBACK CompletionRoutine(
IN DWORD dwError,
IN DWORD cbTransferred,
IN LPWSAOVERLAPPED lpOverlapped,
IN DWORD dwFlags
);
返回值
成功,返回0;
失败,返回SOCKET_ERROR.
IO_ADDRESS LIST_QUERY使用实例:
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#include<winsock2.h>
#include<stdio.h>
#pragma comment(lib, "ws2_32.lib")
int main()
{
WORD wVersionRequested = MAKEWORD(2, 2);//版本
WSADATA wsaDATA;
//打开网络库
if (WSAStartup(wVersionRequested, &wsaDATA) != 0)
{
printf("打开网络库失败!\n");
return -1;
}
SOCKET sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);//创建Socket句柄
struct sockaddr_in si;
si.sin_family = AF_INET;
si.sin_port = htons(9527);//用htons宏将整型转为端口号的无符号整型
si.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
if (SOCKET_ERROR == bind(sock, (const struct sockaddr*)&si, sizeof(si)))
{
int err = WSAGetLastError();//取错误码
printf("服务器bind失败错误码为:%d\n", err);
closesocket(sock);//释放
WSACleanup();//清理网络库
return 0;
}
printf("服务器端bind成功!\n");
char Buf[0x1000] = {
0 };
DWORD dwBytes;
WSAOVERLAPPED ov = {
0 };
ov.hEvent = WSACreateEvent();
int ret = WSAIoctl(sock, SIO_ADDRESS_LIST_QUERY, NULL, 0, Buf, 0x1000, &dwBytes, NULL, NULL);
if (0 != ret)
{
int err = WSAGetLastError();//取错误码
printf("WSAIoctl失败错误码为:%d\n", err);
closesocket(sock);//释放
WSACleanup();//清理网络库
return 0;
}
SOCKET_ADDRESS_LIST* slist = NULL;
SOCKADDR_IN* pAddrInet;
char* pAddrString;
slist = (SOCKET_ADDRESS_LIST*)Buf;
int num = slist->iAddressCount;
if (num > 0)
{
for (int i = 0; i < num; i++)
{
pAddrInet = ((SOCKADDR_IN*)slist->Address[i].lpSockaddr);
pAddrString = inet_ntoa(pAddrInet->sin_addr);
printf("IP%d:%s\r\n", i+1,pAddrString);
}
}
else
{
printf("没有读取到IP信息!/r/n/n");
}
closesocket(sock);//关闭Socket句柄
WSACleanup();//关闭网络库
return 0;
}
边栏推荐
- LeetCode240+312+394
- POJ2421道路建设题解
- 插入排序—直接插入排序和希尔排序
- MySQL row locks and gap locks
- 三维坐标系距离
- "By sharing" northwestern university life service | | bytes a second interview on three sides by HR
- 图片无损压缩软件哪个好用:试试完全免费的JPG-C 图片批量修整压缩减肥工具吧 | 最新jpg批量修整工具下载
- app 自动化 通过工具查看app 元素 (三)
- 华为深度学习课程第九章——卷积神经网络以及案例实践
- Guest brush SQL - 2
猜你喜欢
随机推荐
仿牛客网项目总结
centos 安装php7.4,搭建hyperf,转发RDS
Detailed explanation of the crawler framework Scrapy
I have three degrees, and I have five faces. I was "confessed" by the interviewer, and I got an offer of 33*15.
从底层结构开始学习FPGA(6)----分布式RAM(DRAM,Distributed RAM)
05-SDRAM:仲裁
C语言学习概览(二)
app 自动化 打开app (二)
VoLTE基础学习系列 | 什么是SIP和IMS中的Forking
特殊的日子,值得纪念
special day to remember
类似 MS Project 的项目管理工具有哪些
Dart 异常详解
【HDLBits 刷题】Circuits(1)Combinational Logic
LevelSequence源码分析
Json对象和Json字符串的区别
return;代表含义
LeetCode 415:字符串相加
表的创建、修改与删除
阿里云李飞飞:中国云数据库在很多主流技术创新上已经领先国外