Debian Codegraph @

listings/chapter-5/socket-client.c

raw
1 /***********************************************************************
2 * Code listing from "Advanced Linux Programming," by CodeSourcery LLC *
3 * Copyright (C) 2001 by New Riders Publishing *
4 * See COPYRIGHT for license information. *
5 ***********************************************************************/
6
7 #include <stdio.h>
8 #include <string.h>
9 #include <sys/socket.h>
10 #include <sys/un.h>
11 #include <unistd.h>
12
13 /* Write TEXT to the socket given by file descriptor SOCKET_FD. */
14
15 void write_text (int socket_fd, const char* text)
16 {
17 /* Write the number of bytes in the string, including
18 NUL-termination. */
19 int length = strlen (text) + 1;
20 write (socket_fd, &length, sizeof (length));
21 /* Write the string. */
22 write (socket_fd, text, length);
23 }
24
25 int main (int argc, char* const argv[])
26 {
27 const char* const socket_name = argv[1];
28 const char* const message = argv[2];
29 int socket_fd;
30 struct sockaddr_un name;
31
32 /* Create the socket. */
33 socket_fd = socket (PF_LOCAL, SOCK_STREAM, 0);
34 /* Store the server's name in the socket address. */
35 name.sun_family = AF_LOCAL;
36 strcpy (name.sun_path, socket_name);
37 /* Connect the socket. */
38 connect (socket_fd, &name, SUN_LEN (&name));
39 /* Write the text on the command line to the socket. */
40 write_text (socket_fd, message);
41 close (socket_fd);
42 return 0;
43 }