Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
I'm completely new to C.
And am following this yt
tutorial
on sockets. However he's using the
close(sock)
function. There's 2 problems:
There's no variable called
sock
. The socket is called something else.
I can't find the close function. The compiler is saying that the function doesn't exist
Can you please explain. This question might seem a little too dumb.
Here's the Client code:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
int main()
// Create a socket
int network_socket;
network_socket = socket(AF_INET, SOCK_STREAM, 0);
// Address for the socket
struct sockaddr_in server_address;
server_address.sin_family = AF_INET;
server_address.sin_port = htons(9002);
server_address.sin_addr.s_addr = INADDR_ANY;
int connection = connect(network_socket, (struct sockaddr *) &server_address, sizeof(server_address));
printf("%d\n", connection);
char response[256];
recv(network_socket, &response, sizeof(response), 0);
printf("%s\n", response);
return 0;
–
There's no variable called sock. The socket is called something else.
Yes, it's network_socket in your code. So you want close(network_socket);
.
I can't find the close function. The compiler is saying that the function doesn't exist
You need #include <unistd.h>
, which is where close() is declared. (If you look at man close
you'll see this at the top.)
–
–
You need to pass the socket file descriptor as the argument for close()
. Which, for your code, is network_socket
. So, close()
need to be called as close(network_socket);
Also, you need to use the <unistd.h>
header for the close()
function.
–
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.