Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Q: What happens to socket send/recv buffer sizes after an accept()?
#include <errno.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
void die(const char *f)
{
printf("%s: %s\n", f, strerror(errno));
exit(1);
}
int main(void)
{
int s = socket(AF_INET, SOCK_STREAM, 0);
if(s < 0)
die("socket");
int rcvbuf, sndbuf;
socklen_t optlen = sizeof(rcvbuf);
if(getsockopt(s, SOL_SOCKET, SO_RCVBUF, &rcvbuf, &optlen) < 0)
die("getsockopt (1)");
if(getsockopt(s, SOL_SOCKET, SO_SNDBUF, &sndbuf, &optlen) < 0)
die("getsockopt (1)");
printf("initial rcvbuf: %d\n", rcvbuf);
printf("initial sndbuf: %d\n", sndbuf);
rcvbuf *= 20;
sndbuf *= 20;
if(setsockopt(s, SOL_SOCKET, SO_RCVBUF, &rcvbuf, sizeof(rcvbuf)) < 0)
die("setsockopt");
if(setsockopt(s, SOL_SOCKET, SO_SNDBUF, &sndbuf, sizeof(sndbuf)) < 0)
die("setsockopt");
printf("set rcvbuf to %d\n", rcvbuf);
printf("set sndbuf to %d\n", sndbuf);
struct sockaddr_in sin;
memset(&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_port = htons(12345);
sin.sin_addr.s_addr = INADDR_ANY;
if(bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0)
die("bind");
if(listen(s, 10) < 0)
die("listen");
struct sockaddr_in client_addr;
socklen_t addr_len = sizeof(client_addr);
int s2 = accept(s, (struct sockaddr *)&client_addr, &addr_len);
if(s2 < 0)
die("accept");
printf("accepted connection\n");
optlen = sizeof(rcvbuf);
if(getsockopt(s2, SOL_SOCKET, SO_RCVBUF, &rcvbuf, &optlen) < 0)
die("getsockopt (2)");
if(getsockopt(s2, SOL_SOCKET, SO_SNDBUF, &sndbuf, &optlen) < 0)
die("getsockopt (2)");
printf("new rcvbuf: %d\n", rcvbuf);
printf("new sndbuf: %d\n", sndbuf);
return 0;
}
Linux:
initial rcvbuf: 87380
initial sndbuf: 16384
set rcvbuf to 1747600
set sndbuf to 327680
accepted connection
new rcvbuf: 425984
new sndbuf: 425984
OS X:
initial rcvbuf: 131072
initial sndbuf: 131072
set rcvbuf to 2621440
set sndbuf to 2621440
accepted connection
new rcvbuf: 2629452
new sndbuf: 2629452
Windows 7:
initial rcvbuf: 8192
initial sndbuf: 8192
set rcvbuf to 163840
set sndbuf to 163840
accepted connection
new rcvbuf: 163840
new sndvbuf: 163840
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment