Skip to content

Commit 35fd51c

Browse files
author
Marcel Pursche
committed
Added proper error handling to tcp socket creation and binding.
1 parent 35dee0f commit 35fd51c

File tree

1 file changed

+29
-3
lines changed

1 file changed

+29
-3
lines changed

src/webserver.cpp

Lines changed: 29 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -457,6 +457,7 @@ bool webserver::start(bool blocking)
457457
{
458458
int on = 1;
459459
bool bind_settled = true;
460+
int result = 0;
460461
if(!bind_socket)
461462
{
462463
bind_settled = false;
@@ -501,11 +502,23 @@ bool webserver::start(bool blocking)
501502
else
502503
bind_socket = create_socket (PF_INET, SOCK_STREAM, 0);
503504

504-
setsockopt (bind_socket,
505+
if (bind_socket == -1)
506+
{
507+
cout << "Unable to create socket" << endl;
508+
throw ::httpserver::webserver_exception();
509+
}
510+
511+
result = setsockopt (bind_socket,
505512
SOL_SOCKET,
506513
SO_REUSEADDR,
507514
(const char*) &on, sizeof (on));
508515

516+
if (result != 0)
517+
{
518+
cout << "Unable to set socket option SO_REUSEADDR" << endl;
519+
throw ::httpserver::webserver_exception();
520+
}
521+
509522
if(use_ipv6)
510523
{
511524
#ifdef IPPROTO_IPV6
@@ -517,7 +530,13 @@ bool webserver::start(bool blocking)
517530
#endif
518531
#endif
519532
}
520-
bind(bind_socket, servaddr, addrlen);
533+
result = bind(bind_socket, servaddr, addrlen);
534+
535+
if (result != 0)
536+
{
537+
cout << gettext("Unable to bind socket to port: ") << port << endl;
538+
throw ::httpserver::webserver_exception();
539+
}
521540
}
522541
#ifdef _WINDOWS
523542
unsigned long ioarg = 1;
@@ -528,7 +547,14 @@ bool webserver::start(bool blocking)
528547
fcntl (bind_socket, F_SETFL, flags);
529548
#endif
530549
if(!bind_settled)
531-
listen(bind_socket, 1);
550+
{
551+
result = listen(bind_socket, 1);
552+
if (result != 0)
553+
{
554+
cout << gettext("Unable to listen on port: ") << port << endl;
555+
throw ::httpserver::webserver_exception();
556+
}
557+
}
532558
iov.push_back(gen(MHD_OPTION_LISTEN_SOCKET, bind_socket));
533559
}
534560

0 commit comments

Comments
 (0)