Commit 17018e7b authored by Andrey Vagin's avatar Andrey Vagin Committed by Cyrill Gorcunov

socket_listen: add workaround for EADDRINUSE

crtools doesn't restore sockopts, so if a test is executed in
a second time bind() may return EADDRINUSE
Signed-off-by: 's avatarAndrey Vagin <avagin@openvz.org>
Signed-off-by: 's avatarCyrill Gorcunov <gorcunov@openvz.org>
parent 3ca88151
......@@ -19,11 +19,12 @@ const char *test_author = "Stanislav Kinsbursky <skinsbursky@opernvz.org>";
#include <sys/socket.h>
#include <arpa/inet.h> /* for sockaddr_in and inet_ntoa() */
#include <wait.h>
#define PORT 8880
static int port = 8880;
int init_client(char *servIP, unsigned short servPort);
int accept_server(int sock);
int init_server(int port);
int init_server();
#define BUF_SIZE 1024
......@@ -38,7 +39,7 @@ int main(int argc, char **argv)
test_init(argc, argv);
if ((fd_s = init_server(PORT)) < 0) {
if ((fd_s = init_server()) < 0) {
err("initializing server failed");
return 1;
}
......@@ -57,7 +58,7 @@ int main(int argc, char **argv)
* Chiled is client of TCP connection
*/
close(fd_s);
fd = init_client("127.0.0.1", PORT);
fd = init_client("127.0.0.1", port);
if (fd < 0)
return 1;
......@@ -108,16 +109,15 @@ error:
return -1;
}
int init_server(int port)
int init_server()
{
struct sockaddr_in addr;
int sock;
int yes = 1;
int yes = 1, ret;
memset(&addr,0,sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr("127.0.0.1");
addr.sin_port = htons(port);
sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sock == -1) {
err ("socket() failed %m");
......@@ -129,7 +129,20 @@ int init_server(int port)
return -1;
}
if (bind(sock, (struct sockaddr *) &addr, sizeof(addr)) == -1) {
while (1) {
addr.sin_port = htons(port);
ret = bind(sock, (struct sockaddr *) &addr, sizeof(addr));
/* crtools doesn't restore sock opts, so we need this hack */
if (ret == -1 && errno == EADDRINUSE) {
test_msg("The port %d is already in use.\n", port);
port++;
continue;
}
break;
}
if (ret == -1) {
err ("bind() failed %m");
return -1;
}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment