Created
March 5, 2014 22:33
-
-
Save kotaroito/9378091 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdlib.h> | |
#include <stdio.h> | |
#include <string.h> | |
#include <unistd.h> | |
#include <stddef.h> | |
#include <sys/socket.h> | |
#include <sys/un.h> | |
#include "error.h" | |
#define SOCK_PATH "/tmp/hello.socket" | |
#define BUFFER_SIZE 1024 | |
int main(void) | |
{ | |
int sfd, cfd, size; | |
struct sockaddr_un s_addr, peer_addr; | |
socklen_t peer_addr_size; | |
char buf[BUFFER_SIZE]; | |
int read_size; | |
memset(&s_addr, 0, sizeof(s_addr)); | |
memset(&peer_addr, 0, sizeof(peer_addr)); | |
unlink(SOCK_PATH); | |
// create socket | |
s_addr.sun_family = AF_UNIX; | |
strcpy(s_addr.sun_path, SOCK_PATH); | |
if ((sfd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0) | |
err_sys("socket"); | |
// bind | |
size = offsetof(struct sockaddr_un, sun_path) + strlen(s_addr.sun_path); | |
if (bind(sfd, (struct sockaddr*)&s_addr, size) < 0) | |
err_sys("bind"); | |
// listen | |
if(listen(sfd, SOMAXCONN) < 0) | |
err_sys("listen"); | |
// accept socket | |
peer_addr_size = sizeof(peer_addr_size); | |
if ((cfd = accept(sfd, (struct sockaddr*)&peer_addr, &peer_addr_size)) < 0 ) | |
err_sys("accept"); | |
{ | |
read_size = read(cfd, buf, BUFFER_SIZE); | |
printf("%s\n", buf); | |
} | |
close(cfd); | |
close(sfd); | |
unlink(SOCK_PATH); | |
return EXIT_SUCCESS; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment