What you will learn
- What
close()does to a socket and to the connection. - How
shutdown()gives you a half-closed connection, and when that’s essential. - How to find the peer’s address with
getpeername()and your own withgetsockname(). - How to get the local machine’s name with
gethostname().
close(): release the descriptor
#include <unistd.h>
int close(int fd);
close() frees the descriptor. If it was the last descriptor referring to that socket (remember fork() and dup() can create copies), the kernel starts closing the connection: it sends any data still in the send buffer and then a FIN. The peer’s recv() returns 0 after it has read everything you sent.
After close(), any attempt by the peer to send to you results in a reset, and your descriptor number may be reused by the next open(), socket() or accept().
One gotcha: if unread data is still sitting in your receive buffer when you close, Linux sends a reset (RST) instead of a graceful FIN, and the peer may lose data it hadn’t yet read. Read until recv() returns 0 before closing when that matters.
shutdown(): close one direction
#include <sys/socket.h>
int shutdown(int sockfd, int how);
how | Effect |
|---|---|
SHUT_RD | No more receiving. Incoming data is discarded. |
SHUT_WR | No more sending. The peer gets end-of-stream (recv() returns 0) once it has read everything. You can still receive. |
SHUT_RDWR | Both. |
shutdown() acts on the connection, not on a descriptor: it takes effect even if other processes still hold copies of the socket. It does not free the descriptor; you still call close() afterwards.
Why half-close matters
Imagine a client that uploads a file of unknown length and then wants the server’s checksum of it. The server reads until end-of-stream and only then replies. If the client close()d to signal “done”, it couldn’t read the reply. With SHUT_WR it can:
send_all(fd, file_data, file_len);
shutdown(fd, SHUT_WR); /* "that's everything" - server's recv() returns 0 */
char reply[128];
ssize_t n = recv(fd, reply, sizeof reply, 0); /* still allowed */
close(fd);
The shout client in the next lesson uses exactly this pattern.
getpeername(): who is on the other end?
int getpeername(int sockfd, struct sockaddr *addr, socklen_t *addrlen);
Fills addr with the remote address of a connected socket. It’s handy when the code that handles a connection isn’t the code that called accept(), for example in a worker thread or a child process:
void log_peer(int fd)
{
struct sockaddr_storage peer;
socklen_t len = sizeof peer;
char host[NI_MAXHOST], port[NI_MAXSERV];
if (getpeername(fd, (struct sockaddr *)&peer, &len) == -1) {
perror("getpeername"); /* ENOTCONN if not connected */
return;
}
if (getnameinfo((struct sockaddr *)&peer, len, host, sizeof host,
port, sizeof port, NI_NUMERICHOST | NI_NUMERICSERV) == 0)
printf("peer %s port %s\n", host, port);
}
getsockname(): who am I on this socket?
Same signature, but returns the local address and port. Use it to learn the ephemeral port a client got, or which local interface address the kernel chose for an outgoing connection:
struct sockaddr_storage me;
socklen_t len = sizeof me;
getsockname(fd, (struct sockaddr *)&me, &len);
gethostname(): the machine’s name
int gethostname(char *name, size_t len);
char name[256];
if (gethostname(name, sizeof name) == 0) {
name[sizeof name - 1] = '\0'; /* not guaranteed terminated if truncated */
printf("this machine is %s\n", name);
}
You can feed the result to getaddrinfo() to find the machine’s own addresses, though on many systems that just yields a loopback entry from /etc/hosts. For the real interface list use getifaddrs().
Key takeaways
close()releases a descriptor; the connection ends when the last copy is closed.shutdown(fd, SHUT_WR)signals end-of-stream while still letting you read the reply.shutdown()affects the connection for everyone; it doesn’t free the descriptor.getpeername()gives the remote address,getsockname()the local one,gethostname()the machine’s name.
Exercises
- Write a client that sends a few lines to
nc -l 9000, callsshutdown(SHUT_WR), and then prints whateverncsends back. Type a reply inncto test it. - In a forking server, have the child call
getpeername()and print the client’s address and port. - Print the result of
gethostname()and then resolve it with your lookup tool from lesson 5. Compare withip addr.
Quiz
- A parent process calls
close(client)afterfork(), while the child still usesclient. Is the connection closed? - What does the peer observe after you call
shutdown(fd, SHUT_WR)? - Which call tells a client which ephemeral port it was given?
Show answers
- No. The child still holds a descriptor for the same socket, so the connection stays open until the child closes it too.
- Once it has read all data sent so far, its
recv()returns 0 (end-of-stream). It can still send to you. getsockname()on the connected socket.