-
Notifications
You must be signed in to change notification settings - Fork 162
/
Copy pathclient.c
92 lines (65 loc) · 2.15 KB
/
client.c
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#define _XOPEN_SOURCE 700
#include "assert.h"
#include "stdbool.h"
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include <sys/socket.h>
#include <sys/un.h> /* sockaddr_un */
#include "unistd.h"
int main(int argc, char** argv) {
/* Name of the socket file server and client must agree on it. */
char name[] = "socket.tmp";
/* Sockets are accessible via file descriptors. */
int sockfd;
int len;
//this is the struct used by UNix addresses
struct sockaddr_un address;
char ch_init = 'a';
char ch = ch_init;
/*
#socket
Create the socket, and get a file descrpitor to it.
This must be done by both clients and servers.
int socket(int domain, int type, int protocol);
- protocol:
For a given domain, select which protocol id to use.
`0` uses a default protocol for the domain.
Many domains have a single protocol.
Other do not, for example `AF_INET` has both `tcp` adn `udp`.
To get a protocol id, use `struct protoent *protoent = getprotobyname('tcp')`,
and then extract `protoent->p_proto`.
*/
sockfd = socket(AF_UNIX, SOCK_STREAM, 0);
if (sockfd == -1) {
perror("socket");
exit(EXIT_FAILURE);
}
/*
# connect
Request connection to the socket on the given address.
If the socket file does not exist fails.
*/
/* type of socket */
address.sun_family = AF_UNIX;
/* give a name to the socket */
strcpy(address.sun_path, name);
len = sizeof(address);
if (connect(sockfd, (struct sockaddr*)&address, len) == -1) {
perror("connect");
exit(EXIT_FAILURE);
}
if (write(sockfd, &ch, 1) == -1) {
perror("write");
exit(EXIT_FAILURE);
}
if (read(sockfd, &ch, 1) == -1) {
perror("read");
exit(EXIT_FAILURE);
}
/* You should close the connection on both client and server. */
close(sockfd);
/* Assert that the server did its job of increasing the char we gave it. */
assert(ch == ch_init + 1);
exit(EXIT_SUCCESS);
}