I am facing this problem of Binding to socket. 1st instance works properly i.e. socket() returns success and hence forth bind() and listen(), accept() and hence recv() - All fine till here. 2nd instance throw error while binding "Address already in use"
I went through all the post earlier on this and i dont see any specific solution provided on the same.
My code is as below :-
if((status = getaddrinfo(NULL,"8080",&hints,&servinfo))!=0){
ALOGE("Socket:: getaddrinfo failed %s\n",strerror(errno));
return NULL;
}
server_sockfd = socket(servinfo->ai_family, servinfo->ai_socktype, servinfo->ai_protocol);
if(server_sockfd == -1) {
ALOGE("Socket:: Scoket System Call failed %s\n",strerror(errno));
return NULL;
}
if ((setsockopt(server_sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(int))) < 0)
{
ALOGE("Socket:: setsockopt failed %s\n",strerror(errno));
return NULL;
}
ret = bind(server_sockfd, servinfo->ai_addr,servinfo->ai_addrlen);
if(ret!=0) {
ALOGE("Socket:: Error Binding on socket %s\n",strerror(errno));
return NULL;
}
This code runs on android platform.
I have properly closed each session before opening a new session as below :-
ret = shutdown(client_sockfd,0);
if(ret != 0)
ALOGE("Socket:: Shutdown Called%s\n",strerror(errno));
I tried with close as well but it did not work.
Surprisingly the error does not disappear even when we try to open the socket after long time (as per TIME_WAIT logic)
Could anyone please guide me to proper call or API or Logic(in code and not on command line apart from directly killing the process) to handle this situation ?
close()
onserver_sockfd
? Where is the code that is callingclose()
onclient_sockfd
? Again, please provide an MCVE showing all relevant code related to your sockets. – Remy Lebeau