Sreeraj Chundayil
Sreeraj Chundayil

Reputation: 5859

Sockets_Client_Server_communication_Linux_C

Hi Today I was trying to learn socket communication in c and Linux ,But my below code not working as expected. I am not able to find the problem though I understand where the error is occuring.

server.c

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

char data[100];

int main()
{
    int socket_descrp,server_len;
    socket_descrp = socket(AF_UNIX,SOCK_STREAM,0);
    if(socket_descrp<0)
    {
     perror("server Socket failed\n");
     exit(1);
     }

    struct sockaddr_un server,client; 
    int clientlen;
    server.sun_family = AF_UNIX;
    strcpy(server.sun_path,"mysocket");
    unlink("mysocket");
    server_len = sizeof(server);

    if(bind(socket_descrp,(struct sockaddr *)&server,server_len)<0){
        printf("bind error\n");
        exit(1);

    }

    if(listen(socket_descrp,1)<0)
    {
        printf("listen error\n");
        exit(1);
    }

    if(accept(socket_descrp,(struct sockaddr*)&client,&clientlen)<0)
    {
        printf("accept error\n");
        exit(1);
    }



    if(read(socket_descrp,data,99)<0)
    {
        perror("Error occured in reading\n");
        exit(1);
    }
    else if(read(socket_descrp,data,99)==0)
    {
        printf("No bytes are read\n");
        exit(1);
    }
    else
        printf("Reading from client\n");

    printf("The read content is: %s\n",data);



    close(socket_descrp);   
    return 0;

}

client.c

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

char data[100]="Hello World!";

int main()
{
    int socket_descrp,client_len;
    socket_descrp = socket(AF_UNIX,SOCK_STREAM,0);
    if(socket_descrp<0)
    {
     perror("client Socket failed\n");
     exit(1);
     }

    struct sockaddr_un client;

    client.sun_family = AF_UNIX;
    strcpy(client.sun_path,"mysocket");
    client_len = sizeof(client);

    if(connect(socket_descrp,(struct sockaddr*)&client,client_len)<0)
    {
     printf("Connection error\n");
     exit(1);
    }

    if(write(socket_descrp,data,strlen(data))<0)
    {
        printf("Error writing to the socket\n");
        exit(1);
    }

    return 0;

}

The error message printed is "Error occured in reading: invalid argument" on the server executable file. I am not able to understand why can't it read. Client executable is not printing any error message. I spent nearly 2 hours trying to find the problem. :(

Upvotes: 0

Views: 54

Answers (1)

user58697
user58697

Reputation: 7923

You cannot read from the server socket. accept returns a socket to communicate through:

    client_sock = accept(socket_descrp, ...);
    read(client_sock, ...);

Upvotes: 2

Related Questions