getsockopt函數(shù)用于獲取套接字選項(xiàng)的當(dāng)前值,而setsockopt函數(shù)用于設(shè)置套接字選項(xiàng)的值。它們的使用方法如下:
getsockopt函數(shù)的原型:int getsockopt(int sockfd, int level, int optname, void *optval, socklen_t *optlen);
參數(shù)說(shuō)明:
示例代碼:
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
int main() {
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
int optval;
socklen_t optlen = sizeof(optval);
// 獲取TCP_NODELAY選項(xiàng)的當(dāng)前值
getsockopt(sockfd, IPPROTO_TCP, TCP_NODELAY, &optval, &optlen);
printf("TCP_NODELAY: %d\n", optval);
// 獲取SO_RCVBUF選項(xiàng)的當(dāng)前值
getsockopt(sockfd, SOL_SOCKET, SO_RCVBUF, &optval, &optlen);
printf("SO_RCVBUF: %d\n", optval);
return 0;
}
setsockopt函數(shù)的原型:int setsockopt(int sockfd, int level, int optname, const void *optval, socklen_t optlen);
參數(shù)說(shuō)明:
示例代碼:
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
int main() {
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
int optval = 1;
socklen_t optlen = sizeof(optval);
// 設(shè)置TCP_NODELAY選項(xiàng)為1
setsockopt(sockfd, IPPROTO_TCP, TCP_NODELAY, &optval, optlen);
// 設(shè)置SO_RCVBUF選項(xiàng)為8192
optval = 8192;
setsockopt(sockfd, SOL_SOCKET, SO_RCVBUF, &optval, optlen);
return 0;
}
注意:在使用這些函數(shù)時(shí),需要包含相應(yīng)的頭文件(如sys/socket.h
和netinet/in.h
),并確保在編譯時(shí)鏈接相應(yīng)的庫(kù)(如使用-lsocket
選項(xiàng))。