1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include <sys/types.h>
5 #include <sys/socket.h>
6 #include <netinet/in.h>
7 #include <netinet/ip.h>
8 
9 #define PORT 12345
10 
11 int
12 main (int argc, char **argv)
13 {
14   int fd;
15   struct sockaddr_in sa;
16   struct msghdr msg;
17   struct iovec iov[2];
18 
19   fd = socket (AF_INET, SOCK_DGRAM, 0);
20   if (fd == -1)
21     {
22       perror ("socket()");
23       exit (EXIT_FAILURE);
24     }
25 
26   sa.sin_family = AF_INET;
27   sa.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
28   sa.sin_port = htons (PORT);
29   if (connect (fd, (struct sockaddr *) &sa, sizeof (sa)) == -1)
30     {
31       perror ("connect ()");
32       exit (EXIT_FAILURE);
33     }
34 
35   // Create msg_hdr. Oops, we forget to set msg_name...
36   msg.msg_namelen = 0;
37   iov[0].iov_base = "one";
38   iov[0].iov_len = 3;
39   iov[1].iov_base = "two";
40   iov[1].iov_len = 3;
41   msg.msg_iov = &iov[0];
42   msg.msg_iovlen = 2;
43   msg.msg_control = NULL;
44   msg.msg_controllen = 0;
45 
46   size_t s = sendmsg (fd, &msg, 0);
47 
48   // Note how we now do set msg_name, but don't set msg_flags.
49   // The msg_flags field is ignored by sendmsg.
50   msg.msg_name = NULL;
51 
52   fd = socket (AF_INET, SOCK_DGRAM, 0);
53   if (fd == -1)
54     {
55       perror ("socket()");
56       exit (EXIT_FAILURE);
57     }
58 
59   if (connect (fd, (struct sockaddr *) &sa, sizeof (sa)) == -1)
60     {
61       perror ("connect ()");
62       exit (EXIT_FAILURE);
63     }
64 
65   s = sendmsg (fd, &msg, 0);
66   if (s == -1)
67     {
68       perror ("sendmsg ()");
69       exit (EXIT_FAILURE);
70     }
71   else
72     fprintf (stderr, "sendmsg: %d\n", (int) s);
73 
74   return 0;
75 }
76