Why am I getting a bind error in my socket programs? Is it because I am not closing the sockets correctly?
I am writing simple server and client socket programs. Sometimes I get a binding error in my server program and sometimes it works as expected.
Below is my code for the server
int Socket;
struct sockaddr_in Server;
Socket = socket(AF_INET, SOCK_STREAM, 0);
if(Socket == -1){
printf("Socket error\n");
}
Server.sin_addr.s_addr = inet_addr("127.0.0.1");
Server.sin_family = AF_INET;
Server.sin_port = htons(50000);
if(connect(Socket, (struct sockaddr *)&Server, sizeof(Server)) < 0){
printf("Connection Error\n");
return 1;
}
char Buf[100];
while(1){
memset(Buf, '\0', sizeof(Buf));
if(recv(Socket, &Buf, 100, 0) < 0){
printf("Error to receive\n");
close(Socket);
return 1;
}
if(!strncmp(Buf, "quit\n", 5))
break;
}
close(Socket);
return 0;
And my server code:
int Socket;
struct sockaddr_in server_address, myClient;
Socket = socket(AF_INET, SOCK_STREAM, 0);
if(Socket == -1){
printf("Socket Erro\n");
return 1;
}
memset(&server_address, '0', sizeof(server_address));
server_address.sin_addr.s_addr = htonl(INADDR_ANY);
server_address.sin_family = AF_INET;
server_address.sin_port = htons(50000);
if(bind(Socket, (struct sockaddr*)&server_address, sizeof(server_address)) < 0){
printf("bind error\n");
return 1;
}
listen(Socket, 10);
int nSocket;
nSocket = accept(Socket, (struct sockaddr*)NULL, NULL);
if(nSocket < 0){
perror("Accept Failed");
return 1;
}
char Buf[100];
while(1){
memset(Buf, '\0', sizeof(Buf));
fgets(&Buf[0], 100, stdin);
int temp = strchr(Buf, '\n') - Buf;
write(nSocket, Buf, temp+1);
if(!strcmp(Buf, "quit\n"))
break;
}
close(Socket);
return 0;
Sometimes when I start the server I get a binding error and sometimes I don't. This usually happens when I leave the server and start it up again. Maybe because I am not closing the sockets correctly? Maybe because I am closing the socket on both sides?
source to share
I have fixed the error. The problem was that I tried to start the server again right after I left it. This caused problems with binding the socket again, as the OS made it unavailable for a short period of time after the socket was closed.
After:
Socket = socket(AF_INET, SOCK_STREAM, 0);
I added the following lines to the server program after
int enable = 1;
if (setsockopt(Socket, SOL_SOCKET, SO_REUSEADDR, &(int){ 1 }, sizeof(int)) < 0)
error("setsockopt(SO_REUSEADDR) failed");
I also eliminated many bugs regarding error handling as pointed out by @EJP that didn't directly cause my problem.
source to share