I have to write some code which does the following: client reads input from keyboard and sends the string to the server. Server prints client's IP and the string. Compile time is fine, but when I run the code there's bind error "no such file or directory" I already checked beej's guide and other questions on the forum, but couldn't solve the issue. Any help is appreciated.
EDIT: I made the changes you told me to do except to control the return value of read and write because the program doesn't enter the while loop! also, setsockopt doesn't work.
#include<unistd.h>
#include<string.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<stdio.h>
#include<sys/un.h>
int main(void)
{
int fd1,fd2,test,lun,n,enable=1;
socklen_t len;
struct sockaddr_un indirizzo_serv, indirizzo_cl;
char buf[100]={0},temp[100]={0};
fd1=socket(PF_LOCAL,SOCK_STREAM,0); //creo socket locale
if(fd1<0)
perror("Errore nella creazione del socket\n");
else printf("Socket OK\n");
indirizzo_serv.sun_family=AF_LOCAL;
strcpy(indirizzo_serv.sun_path,"/tmp/socket1000");
//lun=strlen(indirizzo_serv.sun_path)+sizeof(indirizzo_serv.sun_family);
if(setsockopt(fd1,SOL_SOCKET,SO_REUSEADDR,&enable,sizeof(int))<0)
perror("Errore in setsockopt REUSEADDR\n");
test=bind(fd1,(struct sockaddr*)&indirizzo_serv,sizeof(indirizzo_serv));
if(test==0){
printf("Bind OK\n");
test=listen(fd1,2);
if(test==0){
printf("listen OK\n");
len=sizeof(struct sockaddr_un);
while(1){
fd2=accept(fd1,(struct sockaddr*)&indirizzo_cl,&len);
if(fd2<0)
perror("\nErrore nella accept\n");
else printf("Accept OK\n");
write(STDOUT_FILENO,"Client - Inserire la stringa da inviare al server: \n",strlen("Client - Inserire la stringa da inviare al server: \n"));
read(STDIN_FILENO,buf,sizeof(buf));
write(fd2,buf,strlen(buf));//write(fd1,buf,strlen(buf));
read(fd2,buf,strlen(buf));
sprintf(temp,"Server - IP del client: %s\n",indirizzo_cl.sun_path);
write(STDOUT_FILENO,temp,strlen(temp));
memset(buf,0,100);
memset(temp,0,100);
}
}
else perror("Errore nella listen\n");
}
else perror("Errore nella bind\n");
unlink(indirizzo_serv.sun_path);//close(fd1);
return 0;
}
The compilation still has issues (test=0
=> test==0
; int len;
=> socklen_t len;
(wrong signedness)). You should compile with -Wall
and sort them out before asking.
Your error is most likely due a missing directory in the path.
Substituting a sure-to-exist path such as /tmp/socket1
makes it work on my PC.