CodeBlanks Logo Icon CodeBlanks

send and recv

Learn data exchange with send and recv.

send and recv

send(fd, buf, n, 0) sends n bytes to a connected socket. The return value is the number of bytes sent. recv(fd, buf, n, 0) reads up to n bytes from the socket.

The last parameter 0 is the default flag; options like MSG_NOSIGNAL also exist. recv returns 0 when the connection closes. read and write also work with sockets; send/recv add flag support.

socketpair

socketpair(AF_UNIX, SOCK_STREAM, 0, sv) creates two connected sockets and writes them to sv[0] and sv[1]. What one writes, the other reads.

This is ideal for communication within the same process or between parent and child after fork. You test quickly without setting up server-client: send(sv[0], msg, n, 0) writes, recv(sv[1], buf, n, 0) reads. No network address or bind needed; the connection is ready.

Practice Exchange data with socketpair

Create two sockets with int sv[2]; socketpair(AF_UNIX, SOCK_STREAM, 0, sv);. Write with send(sv[0], "merhaba", 7, 0);. Read with char buf[16]; memset(buf, 0, sizeof(buf)); recv(sv[1], buf, 7, 0);. Print with printf("%s\n", buf);.

Starter code

main.c
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>

// Create two sockets with socketpair
// Write with send, read with recv
// Print buf

int main(void) {
    return 0;
}

Sample solution

main.c
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>

int main(void) {
    int sv[2];
    socketpair(AF_UNIX, SOCK_STREAM, 0, sv);
    send(sv[0], "merhaba", 7, 0);
    char buf[16];
    memset(buf, 0, sizeof(buf));
    recv(sv[1], buf, 7, 0);
    printf("%s\n", buf);
    close(sv[0]);
    close(sv[1]);
    return 0;
}

Expected output

merhaba

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match data exchange functions

Term Meaning
send Sends data
recv Receives data
socketpair Two connected sockets
MSG_NOSIGNAL Signal block

2 What does recv return when the connection closes?

  • 0 Correct answer
  • -1
  • 1
  • EOF

Explanation: recv returns 0 when the connection closes.

3 send call

Question
send(____, msg, 7, 0);
Answer
send(sv[0], msg, 7, 0);

Explanation: send(sv[0], ...) writes to the first socket.

All lessons in Advanced