码迷,mamicode.com
首页 > 其他好文 > 详细

unix域套接字的UDP网络编程

时间:2014-10-31 20:46:30      阅读:239      评论:0      收藏:0      [点我收藏+]

标签:unix   网络编程   udp   unix域套接字   

unix域套接字的UDP网络编程,服务端如下:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/un.h>

#define SA struct sockaddr
#define PATHNAME "/tmp/unixudp"

void err_sys(const char *errmsg);

int main(void)
{
    int sockfd;
    struct sockaddr_un servaddr, cliaddr;
    char buf[BUFSIZ];
    ssize_t n;
    socklen_t len = sizeof(cliaddr);

    if ((sockfd = socket(AF_LOCAL, SOCK_DGRAM, 0)) == -1)
        err_sys("socket");

    bzero(&servaddr, sizeof(servaddr));
    unlink(PATHNAME);
    servaddr.sun_family = AF_LOCAL;
    strncpy(servaddr.sun_path, PATHNAME, sizeof(servaddr.sun_path) - 1);

    if (bind(sockfd, (SA *)&servaddr, sizeof(servaddr)) == -1)
        err_sys("bind");

    for(;;){
        n = recvfrom(sockfd, buf, sizeof(buf), 0, (SA *)&cliaddr, &len);
        if (n == -1)
            err_sys("recvfrom");
        else
            printf("%s\n", buf);

        if (sendto(sockfd, buf, n, 0, (SA *)&cliaddr, sizeof(cliaddr)) != n)
            err_sys("sendto");

    }
    exit(0);
}

void err_sys(const char *errmsg)
{
    perror(errmsg);
    exit(1);
}

客户端程序:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/un.h>

#define SA struct sockaddr
#define PATHNAME "/tmp/unixudp"

void err_sys(const char *errmsg);

int main(void)
{
    int sockfd;
    struct sockaddr_un servaddr, localaddr;
    char buf[BUFSIZ], s[] = "hello china";
    ssize_t n;

    if ((sockfd = socket(AF_LOCAL, SOCK_DGRAM, 0)) == -1)
        err_sys("socket");

    bzero(&localaddr, sizeof(localaddr));
    localaddr.sun_family = AF_LOCAL;
    strncpy(localaddr.sun_path, tmpnam(NULL), sizeof(localaddr.sun_path) - 1);

    if (bind(sockfd, (SA *)&localaddr, sizeof(localaddr)) == -1)
        err_sys("bind");

    bzero(&servaddr, sizeof(servaddr));
    servaddr.sun_family = AF_LOCAL;
    strncpy(servaddr.sun_path, PATHNAME, sizeof(servaddr.sun_path) - 1);

    for(;;){
        if (sendto(sockfd, s, strlen(s), 0, (SA *)&servaddr, sizeof(servaddr)) == -1)
            err_sys("sendto");
        if ((n = read(sockfd, buf, sizeof(buf))) == -1)
            err_sys("read");
        else 
            printf("%s\n", buf);
        usleep((rand() % 10) * 10000);
    }

    exit(0);
}

void err_sys(const char *errmsg)
{
    perror(errmsg);
    exit(1);
}


unix域套接字的UDP网络编程

标签:unix   网络编程   udp   unix域套接字   

原文地址:http://blog.csdn.net/fulinus/article/details/40659283

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!