Reputation: 1490
How can I drop connection in plain C after I have sent the data? I have a server which creates socket and waits for connection. After getting connection it sends char array through that socket. After that it should drop the connection and go back to waiting next connection. How can I do that? This is my test code:
int main()
{
char str[100];
int listen_fd, comm_fd;
struct sockaddr_in servaddr;
listen_fd = socket(AF_INET, SOCK_STREAM, 0);
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htons(INADDR_ANY);
servaddr.sin_port = htons(22000);
bind(listen_fd, (struct sockaddr *) &servaddr, sizeof(servaddr));
listen(listen_fd, 10);
comm_fd = accept(listen_fd, (struct sockaddr*) NULL, NULL);
while (1)
{
bzero(str, 100);
write(comm_fd, str, strlen(str) + 1);
}
}
Upvotes: 0
Views: 50
Reputation: 8142
comm_fd = accept(listen_fd, (struct sockaddr*) NULL, NULL);
while (1)
{
bzero(str, 100);
write(comm_fd, str, strlen(str) + 1);
}
The code inside the while
loop is the code that will be repeated constantly...now look where you've placed the call to accept
the new connection. It's outside of the while
loop. As your code currently stands, you'll call it once and then constantly send data at the new connection.
If you put the accept
inside the while
loop and also close
that new connection, like the following code, you should get the result you're looking for.
while (1)
{
comm_fd = accept(listen_fd, (struct sockaddr*) NULL, NULL);
bzero(str, 100);
write(comm_fd, str, strlen(str) + 1);
close(comm_fd);
}
Upvotes: 1