- //unlink(controlsocketname);
- result = bind(control_socket, (struct sockaddr *)&addr, sizeof addr);
-
- if(result < 0 && errno == EADDRINUSE) {
- result = connect(control_socket, (struct sockaddr *)&addr, sizeof addr);
- if(result < 0) {
- logger(LOG_WARNING, _("Removing old control socket."));
- unlink(controlsocketname);
- result = bind(control_socket, (struct sockaddr *)&addr, sizeof addr);
- } else {
- close(control_socket);
- if(netname)
- logger(LOG_ERR, _("Another tincd is already running for net `%s'."), netname);
- else
- logger(LOG_ERR, _("Another tincd is already running."));
- return false;
+#ifdef HAVE_FCHMOD
+ fchmod(fileno(f), 0600);
+#else
+ chmod(pidfilename, 0600);
+#endif
+ // Get the address and port of the first listening socket
+
+ char *localhost = NULL;
+ sockaddr_t sa;
+ socklen_t len = sizeof sa;
+
+ // Make sure we have a valid address, and map 0.0.0.0 and :: to 127.0.0.1 and ::1.
+
+ if(getsockname(listen_socket[0].tcp, (struct sockaddr *)&sa, &len)) {
+ xasprintf(&localhost, "127.0.0.1 port %d", myport);
+ } else {
+ if(sa.sa.sa_family == AF_INET) {
+ if(sa.in.sin_addr.s_addr == 0)
+ sa.in.sin_addr.s_addr = htonl(0x7f000001);
+ } else if(sa.sa.sa_family == AF_INET6) {
+ static const uint8_t zero[16] = {0};
+ if(!memcmp(sa.in6.sin6_addr.s6_addr, zero, sizeof zero))
+ sa.in6.sin6_addr.s6_addr[15] = 1;