dexterous_stranger dexterous_stranger - 5 months ago 58
Linux Question

UDP -- Socket - bind error - Address already in use?

I see that the address is already in use on bind() while the system is starting up.

When I reload the system plenty of times, I see that once in a while like 1 out of 100, I see the following error:


bind failed.Error: Address already in use.


On every reboot of the system - I am closing the socket by using
close(gTx.i4TxSockId)
.

Here is the code, I am not sure on how can I debug this.

I have added netstat -ap to find out what problem was it.

On success, I see:


netstat: /proc/net/tcp6: No such file or directory
udp 0 0 0.0.0.0:syslog 0.0.0.0:* 1562/syslog-ng
udp 0 0 0.0.0.0:49155 0.0.0.0:* 1817/App.exe


On failure, I see:


netstat: /proc/net/tcp6: No such file or directory
udp 0 0 0.0.0.0:45825 0.0.0.0:* 1816/App.exe
udp 0 0 0.0.0.0:syslog 0.0.0.0:* 1562/syslog-ng
udp 0 0 localhost:49155 0.0.0.0:* 1816/App.exe


I have added the following line:

if (setsockopt(gTx.i4TxSockId, SOL_SOCKET, SO_REUSEADDR, &(int){ 1 }, sizeof(int)) < 0)
{
perror("Failed in SO_REUSEADDR");
return;
}


This is not making any difference.

I am using embedded linux - version - 3.8.8

struct sockaddr_in LocalAddr;

gTx.i4TxSockId = socket (AF_INET, SOCK_DGRAM, IPPROTO_UDP);

if (gTx.i4TxSockId < 0)
{
printf("Error in opening socket");
return ;
}

if (setsockopt(gTx.i4TxSockId, SOL_SOCKET, SO_REUSEADDR, &(int){ 1 }, sizeof(int)) < 0)
{
perror("Failed in SO_REUSEADDR");
return;
}

LocalAddr.sin_family = AF_INET;
LocalAddr.sin_addr.s_addr = INADDR_ANY;
LocalAddr.sin_port = HTONS(49155);

/* Bind with the socket */
if (bind (gTx.i4TxSockId, (struct sockaddr *) &LocalAddr, sizeof (struct sockaddr_in)) < 0)
{
/* Failure in binding the UDP socket */
perror("bind failed.Error");
return;
}

Answer

I got to know that I can reserve the port in rcS file -

sysctl -w net.ipv4.ip_local_reserved_ports=49155