0

I am making a tcp server but when I try to close the socket, it is throwing an implicit declaration error.

the code runs fine by removing close(sock_fd) from both tcpserver.c and tcpclient.c.

// tcpserver.c
// including the header files
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <string.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>

//main function
int main() {

    char server_message[100] = "You have reached the server!";

    // creating the server socket
    int sock_fd;
    sock_fd = socket( AF_INET, SOCK_STREAM, 0 );
    
    // defining the socket address
    struct sockaddr_in server_addr;
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(9002);
    server_addr.sin_addr.s_addr = INADDR_ANY;
    
    // bind the socket
    bind(sock_fd, (struct sockaddr *) &server_addr, sizeof(server_addr));
    
    //listen for connections
    listen(sock_fd, 5);
    
    //accept the connection
    int client_socket_fd;
    client_socket_fd = accept(sock_fd, NULL, NULL);
    
    //sending the server message
    send(client_socket_fd,server_message, strlen(server_message),0);
    
    //closing the socket
    close(sock_fd);
    
    return 0;
}

error when compiling

make tcpserver
cc     tcpserver.c   -o tcpserver
tcpserver.c: In function ‘main’:
tcpserver.c:40:9: warning: implicit declaration of function ‘close’; did you mean ‘pclose’? [-Wimplicit-function-declaration]
   40 |         close(sock_fd);
      |         ^~~~~
      |         pclose
Addy
  • 1
  • 1
    You need `#include ` to declare `close`. Read the man page. – Barmar Sep 07 '22 at 23:53
  • The code works fine now, thanks @Barmar. However, after I run both tcpserver and tcpclient, it works fine once. But when I run them again, the client is unable to connect to server and the tcpserver code doesn't terminate. – Addy Sep 08 '22 at 00:04
  • You need to use the `SO_REUSEADDR` socket option if you want to bind the same port again. – Barmar Sep 08 '22 at 00:05
  • Sorry, but I am new to socket programming. So, can you explain a bit why is this happening. And where do I need to add `SO_REUSEADDR`. – Addy Sep 08 '22 at 00:12
  • See https://stackoverflow.com/questions/3229860/what-is-the-meaning-of-so-reuseaddr-setsockopt-option-linux and https://stackoverflow.com/questions/24194961/how-do-i-use-setsockoptso-reuseaddr – Barmar Sep 08 '22 at 00:18

0 Answers0