Socket programming : Accept return 0.

I have a server and client code.
My server says accept and my client says a connect.
After accept when i print inet_ntoa(cin.sin_addr) by running the client on same machine i get 127.0.01 but accept returns a zero. Now when i try to do a recv from the client the recv never waits for a send. It jus returns a -1 and exits. Pls help.

accept will only return 0 if stdin is closed as it returns a file descriptor.

for the client you should be doing

socket(...
connect(...

for the server you should be doing

socket(...
bind(...
listen(....
while (1)
{
     fd=accept(...)
     if (fd!=-1)
     {
     }
}

I'm doing the same and not closing stdin also(explicitly). Still my accept returns a 0 though the server is able to print the client address.

I find that *very* hard to believe. Can you post the exact code from the accept to you printing the filedescriptor and address?

Server code:

#define MYPORT 1034
int main()
{
 struct sockaddr_in sin;
 struct sockaddr_in cin;
 int s = socket(PF_INET,SOCK_STREAM,0);
 sin.sin_family = AF_INET;
 sin.sin_port = htons(MYPORT);
 sin.sin_addr.s_addr = INADDR_ANY;
 memset(sin.sin_zero,'\0',sizeof(sin.sin_zero));
 int check=bind(s,(struct sockaddr *)&sin,sizeof(sin));
 check=listen(s,5);
 addrlen=sizeof(cin);
//My server waits when below line is encountered
 s_client = accept(s,(struct sockaddr *)&cin,&addrlen);
//once client runs and connect is executed accept returns 0
 printf("hi %s\n",inet_ntoa(cin.sin_addr));
 char *buf;
 //the below recv is non blocking, it doesn't wait for client to send.
 recv(s_client,buf,100,0);
}

Client code:

int main(int argc,char *argv[])
{
 struct sockaddr_in sin;
 struct sockaddr_in cin;
 struct hostent *hp;
 hp=gethostbyname(argv[1]);
 cin.sin_family = AF_INET;
 cin.sin_addr = *((struct in_addr *)hp->h_addr);
 cin.sin_port = htons(MYPORT);
 memset(cin1.sin_zero,'\0',sizeof(cin.sin_zero));
 int s = socket(PF_INET,SOCK_STREAM,0);
 int check = connect(s,(struct sockaddr *)&cin,sizeof(cin));
 char buf[100] = "from client";
 int len = strlen(buf);
 int bytes_sent = send(s,buf,len,0);
 printf("%d",bytes_sent); // output is 11
}

I run the server code, it waits for a connect.
Now i run my client code(client.c):
client localhost

now the server waits till client connects then it exits with recv() returning a -1.
client sends the data and quits.

s_client = accept(s,(struct sockaddr *)&cin,&addrlen);

Got the solution:
Actually above line i was executing as

if(s_client=accept(s,(struct sockaddr *)&cin,&addrlen !=-1)

but now i do it as
if((s_client=accept(s,(struct sockaddr *)&cin,&addrlen)!=-1)
Paranthesis was the whole problem creator :smiley:

Thanks a lot.

  1. are you allocating buf first?

  2. if the socket is non blocking you must use select or poll to notify you when to read/write/accept etc.