Lesson 9 of 18 The System Calls

close(), shutdown() and getpeername()

End TCP connections cleanly with close() and shutdown() half-close, and learn who you are talking to with getpeername(), getsockname() and gethostname().

30-40 min beginner 0/18 lessons done
Course contents Lesson 9 of 18 · 0 done
On this page (9 sections)
  1. What you will learn
  2. close(): release the descriptor
  3. shutdown(): close one direction
  4. getpeername(): who is on the other end?
  5. getsockname(): who am I on this socket?
  6. gethostname(): the machine’s name
  7. Key takeaways
  8. Exercises
  9. Quiz

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 with getsockname().
  • 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);
howEffect
SHUT_RDNo more receiving. Incoming data is discarded.
SHUT_WRNo more sending. The peer gets end-of-stream (recv() returns 0) once it has read everything. You can still receive.
SHUT_RDWRBoth.

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

  1. Write a client that sends a few lines to nc -l 9000, calls shutdown(SHUT_WR), and then prints whatever nc sends back. Type a reply in nc to test it.
  2. In a forking server, have the child call getpeername() and print the client’s address and port.
  3. Print the result of gethostname() and then resolve it with your lookup tool from lesson 5. Compare with ip addr.

Quiz

  1. A parent process calls close(client) after fork(), while the child still uses client. Is the connection closed?
  2. What does the peer observe after you call shutdown(fd, SHUT_WR)?
  3. Which call tells a client which ephemeral port it was given?
Show answers
  1. No. The child still holds a descriptor for the same socket, so the connection stays open until the child closes it too.
  2. Once it has read all data sent so far, its recv() returns 0 (end-of-stream). It can still send to you.
  3. getsockname() on the connected socket.

Finished this lesson?

Mark it complete to track your progress (saved in this browser).