UNIX服务器
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <linux/socket.h>
#include <linux/un.h>
#define PROTOCO 0
#define ERRO_ -1
#define ERR_LOG(VAL) do{perror(VAL); exit(EXIT_FAILURE);}while(0)
int main(int argc,const char *argv[])
{
int sockfd = socket(AF_UNIX,SOCK_STREAM,PROTOCO);
int connfd;
char buf[1024] = {0};
int ret;
if(sockfd == ERRO_){
ERR_LOG("socket fail");
}
printf("socket success! sockfd = %d\n",sockfd);
struct sockaddr_un myaddr;
bzero(&myaddr,sizeof(myaddr));
myaddr.sun_family = AF_UNIX;
unlink("/tmp/mysocket");
strcpy(myaddr.sun_path,"/tmp/mysocket");
ret = bind(sockfd,(struct sockaddr *)&myaddr,sizeof(myaddr));
if(ret == ERRO_){
ERR_LOG("bind");
}
printf("success bind!\n");
ret = listen(sockfd,10);
if(ret == ERRO_){
ERR_LOG("listen fail");
}
printf("success listen\n");
while(1){
connfd = accept(sockfd,NULL,NULL);
if(connfd == ERRO_){
ERR_LOG("accept");
}
printf("accept success\n");
char client_buf[64] = {0};
while(1){
ret = read(connfd,buf,sizeof(buf));
if(ret <= 0){
printf("客户端异常退出\n");
break;
}
if(strncmp(buf,"quit",4) == 0){
printf("客户端退出\n");
break;
}
printf("client buf :%s\n",buf);
write(connfd,buf,ret);
bzero(buf,sizeof(buf));
}
close(connfd);
}
close(sockfd);
return 0;
}
UNIX服务器客户端
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <strings.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/un.h>
#define ERR_LOG(VAL) do{perror(VAL);exit(EXIT_FAILURE);}while(0)
#define Maxsize 1024
#define ERR_VAL -1
int main(int argc,const char* argv[])
{
int sockfd;
char buf[Maxsize] = {0};
int connect_return = 0;
int ret = 0;
sockfd = socket(AF_UNIX,SOCK_STREAM,0);
if(sockfd == ERR_VAL){
ERR_LOG("SOCKET");
}
printf("socket success !socket = %d\n",sockfd);
if(access("/tmp/mysocket",F_OK) == -1){
perror("");
exit(1);
}
struct sockaddr_un myaddr;
bzero(&myaddr,sizeof(myaddr));
myaddr.sun_family = AF_UNIX;
strcpy(myaddr.sun_path,"/tmp/mysocket");
connect_return = connect(sockfd,(struct sockaddr*)&myaddr,sizeof(myaddr));
if(connect_return == ERR_VAL){
ERR_LOG("connect");
}
#if 1
while(1){
printf("INPUT >");
fflush(stdout);
ret = read(STDIN_FILENO,buf,sizeof(buf) - 1);
buf[ret] = '\0';
if(buf[strlen(buf) - 1] == '\n'){
buf[strlen(buf) - 1] = '\0';
}
ret = write(sockfd,buf,ret);
if(ret <= 0){
printf("客户端未写数据退出\n");
break;
}
if(strncmp(buf,"quit",4) == 0){
printf("客户端退出\n");
break;
}
bzero(buf,sizeof(buf));
ret = read(sockfd,buf,sizeof(buf) - 1);
buf[ret] = '\0';
if(buf[strlen(buf) - 1] == '\n'){
buf[strlen(buf) - 1] = '\0';
}
printf("服务器回发%s\n",buf);
}
#endif
close(sockfd);
return 0;
}