概述
套接字机制提供两个套接字选项来控制套接字行为。一个接口用来控制选项,另一个接口允许查询一个选项的状态。
1 #include <sys/types.h> 2 #include <sys/socket.h> 3 4 int getsockopt(int sockfd, int level, int optname, void *optval, socklen_t *optlen); 5 int setsockopt(int sockfd, int level, int optname, const void *optval, socklen_t optlen); 6 返回值:若成功则返回0,若出错则返回-1
参数说明:
sockfd:必须指向一个打开的套接字描述符。
level:标识了选项应用的协议。
optname:要设置或获取套接字选项的名字。
optval:指向函数设置或获取值得地址,即保存选项值的缓存区。
optlen:指定了optval指向的对象的大小。
示例1:使用选项SO_RCVBUF和SO_SNDBUF获取缓冲区大小
server.c
1 #include<stdio.h> 2 #include<stdlib.h> 3 #include<sys/types.h> 4 #include<sys/socket.h> 5 #include<unistd.h> 6 #include<arpa/inet.h> 7 #include<netinet/in.h> 8 #include<string.h> 9 #include<errno.h> 10 11 #define N 64 12 #define err_log(log) do{ perror(log); exit(1);}while(0) 13 14 int main(int argc, const char *argv[]) 15 { 16 int sockfd, connectfd; 17 char buf[N]; 18 struct sockaddr_in serveraddr, clientaddr; 19 int optval; 20 socklen_t optlen = sizeof(optval); 21 socklen_t len = sizeof(clientaddr); 22 23 if(argc != 3) 24 { 25 fprintf(stderr, "Usage:%s serverip port", argv[0]); 26 return -1; 27 } 28 sockfd = socket(AF_INET, SOCK_STREAM, 0); 29 if(sockfd < 0) 30 err_log("fail to sockfd"); 31 32 serveraddr.sin_family = AF_INET; 33 serveraddr.sin_addr.s_addr = inet_addr(argv[1]); 34 serveraddr.sin_port = htons(atoi(argv[2])); 35 36 if(getsockopt(sockfd, SOL_SOCKET, SO_SNDBUF, &optval, &optlen) < 0) 37 err_log("fail to getsockopt"); 38 printf("SO_SNDBUF:%d Kn", optval/1024); 39 40 if(getsockopt(sockfd, SOL_SOCKET, SO_RCVBUF, &optval, &optlen) < 0) 41 err_log("fail to getsockopt"); 42 printf("SO_RCVBUF:%d Kn", optval/1024); 43 44 if(bind(sockfd, (struct sockaddr*)&serveraddr, sizeof(serveraddr)) < 0) 45 err_log("fail to bind"); 46 if(listen(sockfd, 5) < 0) 47 err_log("fail to listen"); 48 if((connectfd = accept(sockfd, (struct sockaddr*)&clientaddr, &len)) < 0) 49 err_log("fail to connectfd"); 50 51 printf("client:%s--->%dn", inet_ntoa(clientaddr.sin_addr), ntohs(clientaddr.sin_port)); 52 53 while(1) 54 { 55 if(recv(connectfd, buf, N, 0) < 0) 56 err_log("fail to recv"); 57 if(strncmp(buf, "quit", 4) == 0) 58 break; 59 buf[strlen(buf) - 1] = '