Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

tcp/ip in linux

Hi everyone
I am new to socket programming in linux and i have just written my first few programs. i wrote the following code for a server :

#include
#include
#include
#include
#include
#include

int main()
{
int fd,tempfd;
struct sockaddr_in ss;
struct sockaddr_in temp;
char ch[5];
char ch1[5] = "ABCD";
fd = socket(AF_INET,SOCK_STREAM,0);

ss.sin_family = AF_INET;
ss.sin_addr.s_addr = inet_addr("127.0.0.1");
ss.sin_port = htons(8080);

if(bind(fd,(struct sockaddr *)&ss,sizeof(ss))==-1)
{
fprintf(stderr,"improper bind");
return 0;
}

listen(fd,20);

while(1)
{
tempfd = accept(fd,(struct sockaddr *)&temp,sizeof(temp));
[b]if(tempfd == -1)
fprintf(stderr,"Accept failed");
[/b] if(read(tempfd,&ch,sizeof(ch))<0)
fprintf(stderr,"Crapy read
");
write(tempfd,&ch1,sizeof(ch1));
close(tempfd);
break;
}
return 0;
}

My code is giving an error in the accept() call, saying "Accept failed". Can someone please tell me what is wrong with my program?

Thanks

Comments

  • richfellrichfell Member Posts: 17
    Run this version and you should get more info about the error:

    [code]
    #include
    #include
    #include
    #include
    #include
    #include

    #include
    #include

    int main()
    {
    int fd,tempfd;
    struct sockaddr_in ss;
    struct sockaddr_in temp;
    char ch[5];
    char ch1[5] = "ABCD";
    fd = socket(AF_INET,SOCK_STREAM,0);

    ss.sin_family = AF_INET;
    ss.sin_addr.s_addr = inet_addr("127.0.0.1");
    ss.sin_port = htons(8080);

    if(bind(fd,(struct sockaddr *)&ss,sizeof(ss))==-1)
    {
    fprintf(stderr,"improper bind");
    return 0;
    }

    listen(fd,20);

    while(1)
    {
    tempfd = accept(fd,(struct sockaddr *)&temp,sizeof(temp));
    if(tempfd == -1)
    fprintf(stderr,"Accept failed: %s
    ", strerror(errno));
    if(read(tempfd,&ch,sizeof(ch))<0)
    fprintf(stderr,"Crapy read
    ");
    write(tempfd,&ch1,sizeof(ch1));
    close(tempfd);
    break;
    }

    return 0;
    }
    [/code]
Sign In or Register to comment.