服务器端代码:#include
#include
#include
#include
#include
#include
#include
#include
#include
#define SA struct sockaddr
#define N 64
int main(int argc, char *argv[])
{
int listenfd, connfd, nbyte;
socklen_t addr_len;
char buf[N];
struct sockaddr_un myaddr, peeraddr;
if (argc < 2)
{
printf("input format is: %s ", argv[0]);
exit(1);
}
//int socket(int domain, int type, int protocol);
if ((listenfd = socket(PF_UNIX, SOCK_STREAM, 0)) == -1)
{
perror("socket fail");
exit(1);
}
unlink(argv[1]);
// int bind(int sockfd, const struct sockaddr *addr,
// socklen_t addrlen);
bzero(&myaddr, sizeof(myaddr));
myaddr.sun_family = PF_UNIX;
strcpy(myaddr.sun_path, argv[1]);
if (bind(listenfd, (SA *)&myaddr, sizeof(myaddr)) == -1)
{
perror("bind fail");
exit(1);
}
// int listen(int sockfd, int backlog);
if (listen(listenfd, 5) == -1)
{
perror("listen fail");
exit(1);
}
//int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);
addr_len = sizeof(peeraddr);
if ((connfd = accept(listenfd, (SA *)&peeraddr, &addr_len)) == -1)
{
perror("accept fail");
exit(1);
}
//printf("the client is %s:%d\n", inet_ntoa(peeraddr.sin_addr), ntohs(cli_addr.sin_port));
if ((nbyte = recv(connfd, buf, N, 0)) == -1)
{
perror("read fail\n");
exit(1);
}
printf("recv from %s : %s", peeraddr.sun_path, buf);
close(connfd);
return 0;
}
客户端代码:
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define N 64
#define SA struct sockaddr
int main(int argc, char *argv[])
{
int connfd;
char buf[N];
struct sockaddr_un ser_addr;
if (argc < 2)
{
printf("input format is:%s \n", argv[0]);
exit(1);
}
//int connect(int sockfd, const struct sockaddr *serv_addr,
// socklen_t addrlen);
bzero(&ser_addr, sizeof(ser_addr));
ser_addr.sun_family = PF_UNIX;
strcpy(ser_addr.sun_path, argv[1]);
if ((connfd = socket(PF_UNIX, SOCK_STREAM, 0)) == -1)
{
perror("socket fail\n");
exit(1);
}
if (connect(connfd, (SA *)&ser_addr, sizeof(ser_addr)) == -1)
{
perror("connect fail");
exit(1);
}
strcpy(buf, "this is unix stream socket\n");
send(connfd, buf, N, 0);
return 0;
}
阅读(603) | 评论(0) | 转发(0) |