#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <assert.h> /* * This function reports the error and * exits back to the shell: */ static void bail(const char *on_what) { if (errno != 0) { fputs(strerror(errno), stderr); fputs(": ", stderr); } fputs(on_what, stderr); fputc('\n', stderr); exit(1); } int main(int argc, char **argv) { int z; int s = -1; /* Socket */ int sndbuf = 0; /* 发送缓冲区大小 */ int rcvbuf = 0;/* 接收缓冲区大小 */ socklen_t optlen; /* 设置项长度 (字节)*/ /* *建立一个 TCP/IP socket做测试: */ s = socket(PF_INET, SOCK_STREAM, 0); if (s == -1) bail("socket(2)"); // 设置SO_SNDBUF Size:ss sndbuf = 5000; /* Send buffer size */ z = setsockopt(s, SOL_SOCKET, SO_SNDBUF, &sndbuf, sizeof sndbuf); if (z) bail("setsockopt(s,SOL_SOCKET," "SO_SNDBUF)"); /** 设置SO_RCVBUF 大小: */ rcvbuf = 8192; /* Send buffer size */ z = setsockopt(s, SOL_SOCKET, SO_RCVBUF, &rcvbuf, sizeof rcvbuf); if (z) bail("setsockopt(s,SOL_SOCKET," "SO_RCVBUF)"); /* * 检查上面的设置 * Get socket option SO_SNDBUF: */ optlen = sizeof sndbuf; z = getsockopt(s, SOL_SOCKET, SO_SNDBUF, &sndbuf, &optlen); if (z) bail("getsockopt(s,SOL_SOCKET," "SO_SNDBUF)"); assert(optlen == sizeof sndbuf); /* * 得到设置的socket选项 SO_SNDBUF:*/ optlen = sizeof rcvbuf; z = getsockopt(s, SOL_SOCKET, SO_RCVBUF, &rcvbuf, &optlen); if (z) bail("getsockopt(s,SOL_SOCKET," "SO_RCVBUF)"); assert(optlen == sizeof rcvbuf); /* * 输出缓冲区的大小:*/ printf("Socket s : %d\n", s); printf(" Send buf: %d bytes\n", sndbuf); }