服务器端代码:
#include
#include
#include
#include
#include
#include
#include
#include
#define N 64
typedef struct sockaddr SA;
int main(int argc, char *argv[])
{
int sockfd;
socklen_t addr_len;
char buf[N];
struct sockaddr_un myaddr, peeraddr;
if (argc < 2)
{
printf("input format is : %s \n", argv[0]);
return -1;
}
if ((sockfd = socket(PF_UNIX, SOCK_DGRAM, 0)) == -1)
{
perror("sock fail");
return -1;
}
unlink(argv[1]);
bzero(&myaddr, sizeof(myaddr));
myaddr.sun_family = PF_UNIX;
strcpy(myaddr.sun_path, argv[1]);
if (bind(sockfd, (SA *)&myaddr, sizeof(myaddr)) == -1)
{
perror("bind fail");
return -1;
}
addr_len = sizeof(peeraddr);
recvfrom(sockfd, buf, N, 0, (SA *)&peeraddr, &addr_len);
printf("recv from %s : %s\n",peeraddr.sun_path, buf);
sendto(sockfd, buf, N, 0, (SA *)&peeraddr, addr_len);
return 0;
}
客户端代码如下:
#include
#include
#include
#include
#include
#include
#include
#include
#define N 64
typedef struct sockaddr SA;
int main(int argc, char *argv[])
{
int sockfd;
socklen_t addr_len;
char buf[N];
struct sockaddr_un peeraddr, myaddr;
if (argc < 3)
{
printf("input format is : %s \n", argv[0]);
return -1;
}
if ((sockfd = socket(PF_UNIX, SOCK_DGRAM, 0)) == -1)
{
perror("sock fail");
return -1;
}
// bind myaddr
unlink(argv[2]);
bzero(&myaddr, sizeof(myaddr));
myaddr.sun_family = PF_UNIX;
strcpy(myaddr.sun_path, argv[2]);
if (bind(sockfd, (SA *)&myaddr, sizeof(myaddr)) == -1)
{
perror("bind fail");
return -1;
}
bzero(&peeraddr, sizeof(peeraddr));
peeraddr.sun_family = PF_UNIX;
strcpy(peeraddr.sun_path, argv[1]);
strcpy(buf, "this is unix dgram socket\n");
addr_len = sizeof(peeraddr);
sendto(sockfd, buf, N, 0, (SA *)&peeraddr, addr_len);
recvfrom(sockfd, buf, N, 0, (SA *)&peeraddr, &addr_len);
printf("recv from %s : %s\n", peeraddr.sun_path, buf);
return 0;
}
阅读(1036) | 评论(0) | 转发(1) |