#include <stdio.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
int main()
{
int ret;
int sockfd;
int sockbuflen = 0;
int len = sizeof(sockbuflen);
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd < 0) {
fprintf(stderr, "sockfd get error\n");
return -1;
}
ret = getsockopt(sockfd, SOL_SOCKET, SO_SNDBUF, (void *)&sockbuflen, &len);
if (ret < 0) {
fprintf(stderr, "getsockopt error\n");
return -1;
}
printf("%d\n", sockbuflen);
sockbuflen = 4480;
setsockopt(sockfd, SOL_SOCKET, SO_SNDBUF, (void *)&sockbuflen, len);
ret = getsockopt(sockfd, SOL_SOCKET, SO_SNDBUF, (void *)&sockbuflen, &len);
if (ret < 0) {
fprintf(stderr, "getsockopt error\n");
return -1;
}
printf("%d\n", sockbuflen);
return 0;
}
函數用法,參數選項在《UNIX網絡編程_卷1》第七章,套接字選項中有詳細敘述,須要的能夠查閱。編程
此處須要注意的是:網絡
1.getsockopt() 參數中的len必須初始化成 sizeof(int) ,此處容易跟recvfrom中的addrlen混淆。socket
2.設置sockbuflen以後獲取出來的數值是設置的2倍/*暫時沒有深刻探究緣由*/函數
第一個緣由是由於,看codespa
int sock_getsockopt(struct socket *sock, int level, int optname, char *optval, int *optlen) { struct sock *sk = sock->sk; union { int val; struct linger ling; struct timeval tm; } v; int lv=sizeof(int),len; if(get_user(len,optlen)) return -EFAULT; switch(optname) { /*...*/case SO_SNDBUF: v.val=sk->sndbuf; break; case SO_RCVBUF: v.val =sk->rcvbuf; break; /*...*/default: return(-ENOPROTOOPT); } len=min(len,lv); if(copy_to_user(optval,&v,len)) return -EFAULT; lenout: if(put_user(len, optlen)) return -EFAULT; return 0; }
當len爲0時候,於copy_to_user中的len爲0,因此optval,也就是getsockopt獲取的數值其實是沒變的。code