Skip to content
Advertisement

why my unix domain socket can’t work

there are two simple program to demo the unix domain DGRAM socket.

/* server */
int main(int ac, char *av[])
{
    char buf[10];
    int mpLogFD, len;
    struct sockaddr_un serverAddress;

    if((mpLogFD = socket(AF_LOCAL, SOCK_DGRAM, 0)) < 0)
        mpExit("sock");
    unlink(MPLOGD_SOCK);
    memset(&serverAddress, 0, sizeof(serverAddress));
    serverAddress.sun_family = AF_LOCAL;
    strcpy(serverAddress.sun_path, "/var/run/lsvr.sock");
    if(bind(mpLogFD, (struct sockaddr *)&serverAddress, sizeof(serverAddress)) < 0)
        mpExit("bind");
    perror("svr");
    for(;;){
        if(recvfrom(mpLogFD, buf, sizeof(buf), 0, (struct sockaddr *)&serverAddress, &len) < 0)
            mpExit("recv");
        printf("%sn", buf);
    }
}



/* client */
int main(int ac, char *av[])
{
    int CliFD, len;
    char buf[10];
    struct sockaddr_un cliaddr;

    if((CliFD = socket(AF_LOCAL, SOCK_DGRAM, 0)) == -1)
        mpExit("cli sock");
    memset(&cliaddr, 0, sizeof(cliaddr));
    cliaddr.sun_family = AF_LOCAL;
    strcpy(cliaddr.sun_path, "/var/run/lcli.sock");
    if(bind(CliFD, (struct sockaddr *)&cliaddr, sizeof(cliaddr)))
        mpExit("cli bind");
    len = sizeof(cliaddr);

    sprintf(buf, "12345678n");

    if(sendto(CliFD, buf, sizeof(buf), 0, (struct sockaddr *)&cliaddr, len) < 0)
        mpExit("cli send");
    perror("cli");
}

and the following is the result:

[root@jyl opt]# ./logsvr &            
2033
svr: Success  
[root@jyl opt]# ./logcli              
cli: Success  
[root@jyl opt]#

it seems like nothing wrong here. but, I get nothing from the server.
I don’t know why it can’t run as I expect.

Advertisement

Answer

You should be sending to /var/run/lsvr.sock not to /var/run/lcli.sock.

Also you don’t have to bind in client so comment it out from client:

/*    if(bind(CliFD, (struct sockaddr *)&cliaddr, sizeof(cliaddr)))
            mpExit("cli bind");*/
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement