Weird result of getsockopt
CodeSun via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sun May 24 09:51:43 PDT 2015
Hello guys,
Today, I found a weird problem when I was learning to enable
SO_KEEPALIVE for a specific socket. I use setsockopt to enable
keepalive firstly, and then use getsockopt to show if it is
enabled correctly.
My code snippet is listed below:
Dlang version:
import core.sys.posix.sys.socket;
import core.sys.posix.netinet.in_;
import std.c.stdio;
void main() {
int sfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
int flag = 1;
size_t size;
setsockopt(sfd, SOL_SOCKET, SO_KEEPALIVE, &flag,
cast(socklen_t)flag.sizeof);
flag = 0;
getsockopt(sfd, SOL_SOCKET, SO_KEEPALIVE, &flag,
cast(socklen_t*)&size);
printf("%d\n", flag);
}
C version:
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdio.h>
int main() {
int sfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
int flag = 1;
size_t size;
setsockopt(sfd, SOL_SOCKET, SO_KEEPALIVE, &flag,
(socklen_t)sizeof(flag));
flag = 0;
getsockopt(sfd, SOL_SOCKET, SO_KEEPALIVE, &flag,
(socklen_t*)&size);
printf("%d\n", flag);
return 0;
}
Dlang version always prints 0, which means keepalive is not
enabled, while C version can almost display 1 all the time as
expected.
So is there anything wrong inside the code? If not, whose
behavior is correct?
More information about the Digitalmars-d-learn
mailing list