Click to See Complete Forum and Search --> : bind error during socket programming


jackbh
October 11th, 2009, 05:36 AM
i am kinda new to socket programming. wrote the below code for a server. but getting the bind error everytime. i even tried changing the port number(currently is 13 daytime) but doesnt work. please suggest.

#include"header.h"

int main(int argc,char **argv)
{
int listenfd,connfd,retbind;
struct sockaddr_in servaddr;
char buff[MAX];
time_t ticks;

if((listenfd=socket(AF_INET,SOCK_STREAM,0))<0)
{
printf("socket error");
exit(1);
}
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family=AF_INET;
servaddr.sin_addr.s_addr=htonl(INADDR_ANY); //instead of this use
servaddr.sin_port=htons(13);

if((retbind=bind(listenfd,(struct sockaddr *)&servaddr,sizeof(servaddr)))<0)
{
printf("bind error %d\n",retbind);
exit(1);
}
listen(listenfd,1024);
for(;;)
{
connfd=accept(listenfd,(struct sockaddr *) NULL,NULL);
ticks=time(NULL);
snprintf(buff,sizeof(buff),"%s\r\n",ctime(&ticks));
write(connfd,buff,strlen(buff));
close(connfd);
}
return 0;
}

jackbh
October 11th, 2009, 05:38 AM
forgot to mention .....working in Ubuntu 9.04

Richard.J
October 11th, 2009, 05:43 AM
1. What is the error number you get? Did you try to print the error using perror or strerror?
2. Did you check that the port you are trying to bind to isn't already used? You could do a "netstat -a" to see all used ports.

jackbh
October 11th, 2009, 06:10 AM
netstat -a throws a huge list. not able to interpret. although i don't see a port 13 already used.
i tried perror(). strange enough it shows Permission denied msg.

Richard.J
October 11th, 2009, 06:38 AM
what's the error number, i. e. which value does retbind have after the call to bind()?

Payne747
October 11th, 2009, 06:14 PM
Well the return value of bind() will tell you, but I'm guessing it's because you're trying to bind to a port which might require root privileges.