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