Search code examples
csocketsposix-select

Is a socket still writable even if your network connection is disconnected?


I have this code which I am using to check if a UDP socket is writeable and then it should send some data if it is writeable. I need to send data continuously but it should stop sending whenever my internet connection is disconnected. The application is running on a computer which uses a modem but sometimes the modem hangs up but still my application tries to send the data without it knowing that the internet connection is no longer available.

Open the UDP socket

int socket_fd;
addr.sin_family = AF_INET;
addr.sin_port = htons(999);
addr.sin_addr.s_addr = ip_of_server; 

socket_fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
bind(fd, (struct sockaddr*)&addr, sizeof(addr));

Check if socket is writeable then send some data

struct timeval tv;
fd_set write_fds;
int ready;

tv.tv_sec = 0;
tv.tv_usec = 0;
FD_ZERO(&write_fds);
FD_SET(socket_fd, &write_fds);

ready = select(socket_fd + 1, NULL, &write_fds, NULL, &tv);

if ( ready && FD_ISSET(socket_fd, &write_fds) ) 
{

    //Send data here

}

My problem is select() still reports that the socket is writeable even if I disconnect my internet connection. Is select() really performs that way? Shouldn't it tell you that the socket is not writable since the network connection is already disconnected?

What would be the best solution for this?


Solution

  • UDP socket is always writable.

    You should only use select() to poll whether a tcp socket is writable.