local socket

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

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <netdb.h>
#include <arpa/inet.h>


int main(int argc, char **argv)
{
    struct sockaddr_un address;
    int sock, conn;
    int addrLength;
    int ret = 0;
    char buf[1024] = {0};
    if ((sock = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
    {
        perror("socket");
        exit(0);
    }
    unlink("foo.sock");
    address.sun_family = AF_UNIX;
    strcpy(address.sun_path, "foo.sock");
    addrLength = sizeof(address.sun_family) + strlen(address.sun_path);
    if(bind(sock, (struct sockaddr *) &address, addrLength))
        perror("bind");
    if(listen(sock, 5))
        perror("listen");

conn_loop:
    conn = accept(sock, (struct sockaddr *) &address, &addrLength);
    if (conn > 0)
    {
        while (1)
        {
            ret = recv(conn, buf, sizeof(buf), 0);
            
            if (ret < 0)
            {
                perror("hello\n");
                continue;
            }
    
            if (ret == 0)
            {
                printf ("perr shutdown\n");
                close(conn);
                bzero(buf, sizeof(buf));
                goto conn_loop;
            }

            printf("%s\n", buf);
            bzero(buf, sizeof(buf));
        }
    }
    return 0;

}


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

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <netdb.h>
#include <arpa/inet.h>

#define  SOCK_PATH  "foo.sock"

int main(int argc, char **argv)
{
    int client_fd;
    int len;
    ssize_t  I;
    char *msg = "hello server\n";
    char buf[1024] = {0};
    struct sockaddr_un remote;
    if((client_fd = socket(AF_LOCAL, SOCK_STREAM, 0)) == -1)
    {
        perror("socket()");
        exit(0);
    }
    remote.sun_family = AF_LOCAL;
    strcpy(remote.sun_path, SOCK_PATH);
    len = sizeof(remote);

    if(connect(client_fd, (struct sockaddr *)&remote, len) == -1)
    {
        strerror(errno);
        exit(0);
    }

    while (1)
    {
        if(send(client_fd, msg, strlen(msg), 0) == -1)
        {
            strerror(errno);
            unlink(SOCK_PATH);
            exit(0);
        }
        sleep(2);
    }
}








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值