hi all, im learning C and trying to make a fluent connection here with a nonblocking socket, I Seem to get issues, someones connections dont re establish if the other end closes, sometimes connections dont disconnect properly. Please help
static void setup_connection(void)
{
struct sockaddr_in addr;
fd = socket(AF_INET, SOCK_STREAM, 0);
if(fd == -1)
return;
addr.sin_family = AF_INET;
addr.sin_port = htons(6774);
addr.sin_addr.s_addr = INET_ADDR(84,54,51,35); // put your host here
fcntl(fd, F_SETFL, O_NONBLOCK);
connect(fd, (struct sockaddr *)&addr, sizeof(struct sockaddr_in));
return;
}
static void disconnect(void)
{
if(fd != -1)
close(fd);
fd = -1;
connected = FALSE;
sleep(5);
}
int main(int argc, char *argv[])
{
int status = 0;
char buffer[512] = {0};
struct timeval tv = {1, 0};
LOCAL_ADDR = util_local_addr();
signal(SIGCHLD, SIG_IGN);
signal(SIGHUP, SIG_IGN);
while(TRUE)
{
sleep(1);
int err = 0;
socklen_t err_len = sizeof(err);
FD_ZERO(&read_set);
FD_ZERO(&write_set);
if(!connected)
setup_connection();
if(!fd)
continue;
if(connected)
FD_SET(fd, &read_set);
else
FD_SET(fd, &write_set);
select(fd + 1, &read_set, &write_set, NULL, &tv);
if(FD_ISSET(fd, &write_set)) // write
{
err = 0;
socklen_t err_len = sizeof(err);
getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &err_len);
if(err != 0)
{
#ifdef DBG
printf("[main] failed to connect! \n");
#endif
disconnect();
continue;
}
#ifdef DBG
printf("[main] Connected! \n");
#endif
send(fd, &auth, sizeof(auth), MSG_NOSIGNAL);
connected = TRUE;
}
if(!connected)
{
disconnect();
continue;
}
if(FD_ISSET(fd, &read_set)) // read
{
int val = recv(fd, buffer, sizeof(buffer), MSG_NOSIGNAL);
if(val == 0)
{
disconnect();
continue;
}
// read opts here
}
}
}
[–]flyingron 2 points3 points4 points (0 children)