Unix sockets demo
This commit is contained in:
parent
e07b9a5eff
commit
1a505c032e
5 changed files with 234 additions and 0 deletions
41
socket/client.c
Normal file
41
socket/client.c
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/un.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#define SOCKET_PATH "/tmp/demosocket"
|
||||
|
||||
int main() {
|
||||
int sock_fd;
|
||||
struct sockaddr_un addr;
|
||||
char buffer[100];
|
||||
|
||||
sock_fd = socket(AF_UNIX, SOCK_STREAM, 0);
|
||||
if (sock_fd < 0) {
|
||||
perror("socket");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
memset(&addr, 0, sizeof(struct sockaddr_un));
|
||||
addr.sun_family = AF_UNIX;
|
||||
strncpy(addr.sun_path, SOCKET_PATH, sizeof(addr.sun_path) - 1);
|
||||
|
||||
if (connect(sock_fd, (struct sockaddr *)&addr, sizeof(struct sockaddr_un)) <
|
||||
0) {
|
||||
perror("connect");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
send(sock_fd, "ping\n", 4, 0);
|
||||
|
||||
int bytes = recv(sock_fd, buffer, sizeof(buffer) - 1, 0);
|
||||
if (bytes > 0) {
|
||||
buffer[bytes] = '\0';
|
||||
printf("Client got: %s\n", buffer);
|
||||
}
|
||||
|
||||
close(sock_fd);
|
||||
return 0;
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue