Friday, 19 February 2010

unconnect() a UDP socket

So you've got a UDP socket and you've called connect() on it to make it send or listen to a particular IP address, but then you need to disconnect it again, without destroying it. Why would you want to do that?? Well on some OSes (ie Mac OSX, BSD) if you're connected to UDP socket on a machine you can only do that once with the same address (even when you're using the REUSEADDR stuff). So anyway you can disconnect() or unconnect() your socket by the doing the following:
int disconnect_udp_sock(int fd) {
 struct sockaddr_in sin;        

 memset((char *)&sin, 0, sizeof(sin));
 sin.sin_family = AF_UNSPEC;
 return (connect(fd, (struct sockaddr *)&sin, sizeof(sin)));
}
On some OSes you may get a dodgy return value but according to the connect() man page it's ok.

No comments:

Post a Comment