File: sendmsg.c

package info (click to toggle)
valgrind 1%3A3.16.1-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 158,568 kB
  • sloc: ansic: 746,130; exp: 26,134; xml: 22,708; asm: 13,570; cpp: 7,691; makefile: 6,177; perl: 5,965; sh: 5,665; javascript: 929
file content (75 lines) | stat: -rw-r--r-- 1,538 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>

#define PORT 12345

int
main (int argc, char **argv)
{
  int fd;
  struct sockaddr_in sa;
  struct msghdr msg;
  struct iovec iov[2];

  fd = socket (AF_INET, SOCK_DGRAM, 0);
  if (fd == -1)
    {
      perror ("socket()");
      exit (EXIT_FAILURE);
    }

  sa.sin_family = AF_INET;
  sa.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
  sa.sin_port = htons (PORT);
  if (connect (fd, (struct sockaddr *) &sa, sizeof (sa)) == -1)
    {
      perror ("connect ()");
      exit (EXIT_FAILURE);
    }

  // Create msg_hdr. Oops, we forget to set msg_name...
  msg.msg_namelen = 0;
  iov[0].iov_base = "one";
  iov[0].iov_len = 3;
  iov[1].iov_base = "two";
  iov[1].iov_len = 3;
  msg.msg_iov = &iov[0];
  msg.msg_iovlen = 2;
  msg.msg_control = NULL;
  msg.msg_controllen = 0;

  size_t s = sendmsg (fd, &msg, 0);

  // Note how we now do set msg_name, but don't set msg_flags.
  // The msg_flags field is ignored by sendmsg.
  msg.msg_name = NULL;

  fd = socket (AF_INET, SOCK_DGRAM, 0);
  if (fd == -1)
    {
      perror ("socket()");
      exit (EXIT_FAILURE);
    }

  if (connect (fd, (struct sockaddr *) &sa, sizeof (sa)) == -1)
    {
      perror ("connect ()");
      exit (EXIT_FAILURE);
    }

  s = sendmsg (fd, &msg, 0);
  if (s == -1)
    {
      perror ("sendmsg ()");
      exit (EXIT_FAILURE);
    }
  else
    fprintf (stderr, "sendmsg: %d\n", (int) s);

  return 0;
}