Pete's Log: sockets fun
Entry #555, (Coding, Hacking, & CS stuff)(posted when I was 22 years old.)
oh man ... someday I will fully understand sockets. The entire sockets interface is just full of so much legacy and strangeness. I finally forced myself to figure out something I've been meaning to figure out for some time now. The generic sockets code that everyone sees in OS courses and socket sample code isn't quite right. I've always seen something of this variety:
/* get our local host name */ gethostname(host, sizeof(host)); if (!(hp = gethostbyname(host))) { exit(1); } /* create a socket here */ /* set up address and port */ sin.sin_family = AF_INET; sin.sin_port = htons(port); memcpy(&sin.sin_addr, hp->h_addr_list[0], hp->h_length); /* bind socket to address */ if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) { exit(1); } /* listen or something */
Well, this causes all sorts of trouble when you're trying to do a generic listen on a bound port, because if you try to do a connect to localhost, you're gonna fail, since the socket is only listening on the address returned by gethostname. But for a lot of things you want your listening socket to accept connections to any address associated with your host, such as localhost. Well, how do you figure out how this works? grep. grep is my best friend. So reading some of the sshd source code (since I happen to have it local) and after browing through some of the code in /usr/include/ I finally figure it out. It's fairly simple, but definitely not intuitive, given the above code. The main thing is to do this
sin.sin_addr.s_addr = INADDR_ANY;
instead of the memcpy above. Confusing, mainly, because sin.sin_addr isn't treated as a struct in the above memcpy. I love C, because who cares about types, anyway? It's all memory. So now I think I'm gonna try and figure out what all the various options are you can use with setsockopt. And here I was thinking I had a decent understanding of sockets. There is an absurd amount of stuff about them I don't know. If anyone can recommend a good book about this stuff, I'd appreciate it. Reading man pages, header files, and sample code has gotten me a long way towards knowing how most of this stuff works, but a book would probably go a long way towards greater intuitive understanding. The more time I spend playing with this stuff, the more I start thinking I might want to start focusing on network stuff. I just don't have any idea what kind of research I'd do in that area. I just know I really like this stuff.