Как побороть » address already in use»
Есть сферический код TCP-сервера на луа:
Подключаюсь к нему с помощью
Если развывать соединение, нажимая Ctrl+C в терминале с nc, то всё норм.
Если же разрывать соединение нажимая Ctrl+C в терминале с сервером, то его последующий запуск вываливается с ошибкой «address already in use» в строке с bind. Через минуту-две запускается нормально
Как побороть «address already in use»? Может подкрутить какие-то опции?
PS: сишников скастовал, потомучто только они разбираются в подобной низкоуровневой магии )
Вышеописанное поведение она не меняет. По-прежнему «address already in use» если тушить сервер при подключенном клиенте
SO_LINGER(с нулевым таймаутом)
reuseaddr влияет если сервер биндится к INADDR_ANY. Но т.к. сокет все-равно в полузакрытом состоянии, законектиться к тому же адресу и тому же порту не получится, пока ОС не отпустит сокет их состояния TIME_WAIT (60 сек, как показывает /proc/sys/net/ipv4/tcp_fin_timeout)
Собственно, переформулируя вопрос из ОП-поста: как повлиять на /proc/sys/net/ipv4/tcp_fin_timeout локально, только для моей програмы?
О, заработало! Спасибо)
убирать time_wait в ноль не очень красиво. навесь обработчик сигнала sigint и с нем рви соединение через tcp rst.
Некрасиво только если потом закрывать ненормально. А если в софте реализован graceful shutdown, то без linger вполне можно жить.
Если же разрывать соединение нажимая Ctrl+C в терминале с сервером
То можно зарегистрировать обработчик соответствующего сигнала. А в нём установить флаг is_shutdown. Теперь после ctrl-c будет вызван обработчик, потом server:accept завершится с ошибкой (EINTR), это можно словить и если флажок is_shutdown взведён, мы знаем, что всё ОК, пользователь хочет всё закрыть, закрываем и выходим
Оффтопик. А вне программы эту проблему можно решить?
Есть некрософт, который давно заброшен разработчиком, но к сожалению в продакшне. Время от времени через него проходят данные, не соответствующие ТЗ, и оно намертво виснет. Давно написал ему watchdog, ( проверяет /proc/$pid/schedstat и /proc/$pid/wchan ), который в случае зависания перезапускает ( при необходимости — убивает по kill -9 ). Но часто при повторном запуске вижу в логах то же самое «address already in use», хотя процесс уже убит. В результате watchdog несколько раз в цикле убивает это говно мамонта, пока тому не удаётся взлететь успешно
Можно ли как-то принудительно очистить состояние порта?
Увы, нет. Это в парафаии ядра, что и настраивается таймаутами на соединение и свойство сокета, опциями SO_REUSEPORT и SO_LINGER. Но любой из этих вариантов имеет последствия. SO_REUSEPORT был разработан в первую очередь для балансировки между несколькими процессами на одном порту, SO_LINGER — непосредственно таймаут в состоянии TIME_WAIT.
Как выше писали, самый лучший вариант — писать обработчик завершения программы по сигналу.
убирать time_wait в ноль не очень красиво
А чем это чревато?
навесь обработчик сигнала sigint и с нем рви соединение через tcp rst.
Пример был сферический. Sigint тоже. Скрипт нужен чтобы тестировать разрывы любимого ростелекома. А тут еще ядро свои разрывы добавляет)
пишу через обработчики уже 10 лет И НИ ЕДИНОГО РАЗРЫВА!!11
миллион способов, все зависит от того насколько «схаченное» решение для вас терпимо. можно сниффать сиквенс намбер и слать tcp rst, например из scapy (из удобного), или даже вроде есть специализированные утилиты. если все зависло так что траффика вообще никакого не проходит (ну, хотя бы кип-алайв зафорсить обычно можно — посылаешь со спуфленного адреса) то тогда можно подглядеть нужный сиквенс намбер прямо в ядре, например через systemtap или кастомным модулем. если же вопрос решается SO_LINGER с нулевым таймуатом, то можно его принудительно установить на сокет — пиши модуль для LD_PRELOAD с перехватом bind() например и устанавливай там дополнительные опции на сокет, я так для одного старого проприетарного говна увеличивал очередь необработанных коннектов.
Какой сигнал сработает когда ростелеком разорвет соединение?)
во-первых, если хочешь получить на свои топики нормальные рабочие ответы, давай в них всю информацию, а то сейчас еще выясниться что речь не про сервер TCP, а еще через две страницу — что и вовсе на самом деле у тебя там винда с SUA.
теперь по делу. если у тебя демон умирает когда говнотелеком рвет соединение, ты что-то делаешь не так. расскажи больше.
Источник
address already in use error in mosquitto
I have installed mosquitto server and client packages in my ubuntu machine. When I run command «mosquitto» to run the mosquitto server I am getting an error «Error:address already in use». Why am I getting this error? How can I resolve this?
4 Answers 4
I ran into the same problem, and resolved the situation by killing the process that was running mosquitto. First, locate the mosquitto process id:
This should reveal to you any mosquitto related process. Say for example the process id was 12345, then you could kill it with this:
After that the Error:address already in use message was gone and mosquitto was able to run properly again.
The installation on ubuntu automatically starts the broker for you. Try connecting to check it out:
You will need to install the mosquitto-clients package if you haven’t done so already.
Just wait for 1 minute and the fire shut down command again. here is what I followed and got it working
step 1: journalctl -u mosquitto
step 2: service mosquitto stop //and not systemctl stop mosquito
Just to check if it successfully close use this Optional — step 3 : systemctl status mosquitto.service
step 4: service mosquito start
The package installer sets up mosquitto as a systemd service and automatically starts it running for you. It also configures mosquitto to start on a reboot, so you never need to start it manually.
But sometimes it can be helpful to run it in a console window, such as to test a new configuration file, or to watch the output to see clients make and break connections and things like that. In order to do this, you need to stop the background service, and you can use systemctl to do this:
When you’re done with your testing and want to start the background service back up:
To check it, use the status command:
That shows you that it is running, when it started, the process (Main) PID, and the configuration file that it is using, among other thing.
Источник
Nginx will not start (Address already in use)
I have a problem with nginx. I tried different solutions, but for me nothing work. That is my error:
Can you help me?
7 Answers 7
Probably other process is using specified port:
Get the PID of the process that already using 443. And send signal with kill command.
Aternatively you can do:
Make sure you dont use old syntax:
The above syntax will cause
Correct syntax:
Both above syntax will achieve the same thing, listening on both ipv4 and ipv6.
Another way (from my experience) is just force quit the process that running on that port 443
or if you running on port 80 just change the port to
Hope it helps someone who had the same issue
Alternative using lsof :
Find the PID & kill the process which running on port 443
Thank you for the answer. After running
I realised that I had apache2 running on port 80. This was probably done after I used Certbot to install SSL on the server. I removed Apache2 and the server was up and running.
This did the trick! Thank you again.
I received the above error due to accidentally repeating the listen directive twice within the same server block as follows:
resolved the problem when restarting the server: sudo service nginx start
When I killed the nginx process bind to 80 & 443 ports, the process always reappeared with new PID.
It helped me to temporarily comment this line in /etc/nginx/nginx.conf , restart nginx and then uncomment the line back:
If using a virtual machine, you may just need to restart the virtual machine. I was having the same issues yesterday and I could not get Nginx to start using any of the methods in this post. So I started the virtual machine up this morning, checked the running processes, and I see Nginx running on port 80. I even viewed the status of Nginx yesterday with systemctl and it said failed, but today it is active. Not sure what happened here, but it could be worth a try.
First, we have to check how many services run on port 80. To check that, you could run the following command:
This would show you which service exactly is listening on port 80 and then you can make a decision whether you want to have that service as is or have Nginx instead.
If it is Apache, you will need to decide whether you want to use Apache or Nginx.
If you only want to have Nginx, you need to stop Apache first:
Источник
Ubuntu error with apache: (98)Address already in use
I am getting this error when I try to start Apache in Ubuntu.
I have this in my ports.conf
This is my vhost file
What am I missing?
14 Answers 14
It seems port 80 is already taken. Use another port or try netstat ( grep the result to select only the row with value 80 in it), ps and kill to see what application occupies the port and shut it down.
This would return the following:
tcp6 0 0 . 80 . * LISTEN 1047/apache2
Then run the following command:
(the pid that appears on your particular instance.)
In all cases killing the process may not work, as the process using the port 80 will get restarted and doesn’t allow to use the port. So what can be done is to change the port for apache, if that doesn’t matter.
Two things are to be changed for that:
Open /etc/apache2/ports.conf with any text editor and change the value of the entry Listen 80 to the desired port (e.g. Listen 8080 ).
Change the entry for to the same port number you gave in the /etc/apache2/ports.conf file in /etc/apache2/sites-enabled/000-default (e.g. ).
Make sure that you don’t have the command Listen 80 in more than one place.
In my case, I was getting the same error and the reason was that this command was both in ports.conf and sites-enabled/000-default.
In my case it was nginx (’cause I have it on my server).
pkill the process (nginx?)
Disable whatever virtualhost is binding to port 80 that you don’t want to (nginx?). It’s in /etc/nginx/sites-enabled or /etc/apache2/sites-enabled
sudo kill -9 -2321 (pid) Restart BT Done. no need to make changes in conf. file.
When you restart or start your server via terminal you might have forgot to add sudo before the command.
Use sudo /etc/init.d/apache2 reload instead of /etc/init.d/apache2 reload
I had the same issue with a very different cause. I am running Apache 2.4.7 with PHP 5.5.6 on CentOS 6.5.
I messed up php.ini by having BOTH output_handler=ob_gzhandler AND zlib.output_compression=On (either one, not both, can be set).
So on restarting Apache, it binds to port 80 but nothing else happens. It looks like it is running but php’s error locked it up somewhere.
The clue was to check «php -v» . when I saw it not returning anything (it wrote the error to error_log), I fixed php.ini and Apache was happy again.
Maybe this helps someone.
I got this error on a fresh install of Ubuntu 12.10 when starting apache2.
It’s a bug in the apache2. It gets hung in the background. Here is my walkthrough to where the bugs might be in the software.
Here’s the error I got:
Address already in Use? What could be using it? Check it out:
That means apache2 is preventing apache2 from starting. Bizarre. This will confirm:
Yes, in this case apache2 is running, I was trying to start apache2 a second time on the same port.
What confuses me is that service reports that apache2 is NOT running:
And when you query apache2ctl for its status, it hangs.
So Ubuntu seems to be having trouble managing apache2 on bootup. Time to stop apache2:
A big clue! You try to stop apache2 and it lost the process id! So Ubuntu can’t stop apache2 because it doesn’t know where it is!
You would think a reboot would fix it, but it doesn’t because apache2 starts on boot and hangs. The normal boot process for apache2 is not working right.
So How to fix it?
I was able to fix this by analyzing the ps command output. Notice that the ps command tells us that that process was started by «/etc/rc2.d/S91apache2 start».
That is the offending program that needs a swift kick.
/etc/rc2.d/S91apache2 is the symbolic link used to start apache2 for you when the computer starts. For some reason it seems to be starting apache2 and then hangs. So we’ll have to tell it to not do that.
So go take a look at that /etc/rc2.d/S91apache2 .
It’s a symbolic link that we don’t want it to be there. Do this to prevent apache2 from starting on boot:
Reboot the computer to make sure apache2 doesn’t start and hang. Ok good. Now you COULD put apache2 back the way it was, but that would make it fail again.
Instead, start the apache2 like this:
And the apache2 is back up and serving pages again. There seems to be some serious bugs with apache2/Ubuntu 12.10 that causes apache2 to start and hang. This is a workaround, I suppose the fix is to get newer versions of apache2 and Ubuntu and hope for the best.
Источник