could not bind socket address and port are already in use как исправить

Could not bind socket address and port are already in use как исправить

Pascal
public procedure Bind(ASocket: TIdStackSocketHandle; const AIP: string; const APort: TIdPort; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION); override;C++
public: virtual __fastcall Bind(TIdStackSocketHandle ASocket, const AnsiString AIP, const TIdPort APort, const TIdIPVersion AIPVersion = ID_DEFAULT_IP_VERSION);Parameters
Parameters Description
ASocket: TIdStackSocketHandle Socket handle to bind.
const AIP: string IP address to use for the local network connection.
const APort: TIdPort Port number to use for the local network connection.
const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION IP address family for the IP address.
Description
Bind is an overridden procedure used to set the local network information for the socket handle by assigning the address family, IP address, and port number for the specified socket handle.

ASocket is the socket handle to bind.

AIP is the IP address to use for the local network connection.

APort is the port number to use for the local network connection.

AIPVersion is the IP address family for the specified IP address. The default value (ID_DEFAULT_IP_VERSION) causes the default IP address family for the platform or Operating System to be used.

AIPVersion controls the type of IP address that will be assigned for the local network interface: IPv4 or IPv6. The IPVersionUnsupported method is called when an unknown or invalid value is specified in the AIPVersion argument.

When a new socket handle is created, it does not have enough information to assign the IP address, and port number for the local network connection. Bind causes the information to be updated to uniquely identify the local network interface on the socket handle.

If an application does not care what local address is assigned, the value INADDR_ANY may be used. The protocol stack will assign an appropriate local network address for the socket handle. AIP is used to return the IP address assigned by the protocol stack.

When the port number is zero (0), the protocol stack will assign a unique port number with a value between 1025 and 5000. On Windows Vista and later, the port range is between 49152 and 65535. APort is used to return the value assigned by the protocol stack.

Binding to a port number other than port 0 is discouraged for client applications, since there is a danger of conflicting with another socket already using that port number on the local computer.

Socket handles that require the SO_EXCLUSIVEADDRUSE or SO_REUSEADDR socket option must set option before calling Bind.

Bind provides access to the bind() API in Winsock2. The getsockname() API routine can be used after calling Bind to learn the address and the port number assigned for a socket handle.

Bind is required for an unconnected socket that needs to Listen for remote connections. It is normally used to bind to connection-oriented (stream) or connectionless (datagram) sockets, but may also be used to on a raw socket (SOCK_RAW). Bind is used on a disconnected socket prior to calling Connect or Listen.

For multicast operations, call Bind to assign the local network interface for the sockethandle and then join the multicast group. This order of operations is not required, but it is recommended. Bind is not required for sending data to a multicast group. The sendto, WSASendMsg, and WSASendTo functions implicitly bind the socket to the wildcard address when not already bound.

Bind calls the CheckForSocketError to determine if a socket reponse should result in an exception.

See Also
TIdStackSocketHandle, TIdPort, TIdIPVersion, CheckForSocketError, Connect, Disconnect, Listen, Send, SendTo, SetSocketOption

��� ����� �������� � ������� ����� ��������� «Could not bind socket. Address and port are already in use» � � ������� «socket operation on non-socket»?

Источник

Python: Binding Socket: «Address already in use»

I have a question regarding client socket on TCP/IP network. Let’s say I use

The socket created will be bound to port 5555. The problem is that after ending the connection

Using wireshark, I see the socket closed with FIN,ACK and ACK from both sides, I can’t use the port again. I get the following error:

I wonder how can I clear the port right away so that next time I still can use that same port.

setsockopt doesn’t seem to be able to resolve the problem Thank you!

12 Answers 12

Try using the SO_REUSEADDR socket option before binding the socket.

Edit: I see you’re still having trouble with this. There is a case where SO_REUSEADDR won’t work. If you try to bind a socket and reconnect to the same destination (with SO_REUSEADDR enabled), then TIME_WAIT will still be in effect. It will however allow you to connect to a different host:port.

A couple of solutions come to mind. You can either continue retrying until you can gain a connection again. Or if the client initiates the closing of the socket (not the server), then it should magically work.

Here is the complete code that I’ve tested and absolutely does NOT give me a «address already in use» error. You can save this in a file and run the file from within the base directory of the HTML files you want to serve. Additionally, you could programmatically change directories prior to starting the server

Actually, SO_REUSEADDR flag can lead to much greater consequences: SO_REUSADDR permits you to use a port that is stuck in TIME_WAIT, but you still can not use that port to establish a connection to the last place it connected to. What? Suppose I pick local port 1010, and connect to foobar.com port 300, and then close locally, leaving that port in TIME_WAIT. I can reuse local port 1010 right away to connect to anywhere except for foobar.com port 300.

However you can completely avoid TIME_WAIT state by ensuring that the remote end initiates the closure (close event). So the server can avoid problems by letting the client close first. The application protocol must be designed so that the client knows when to close. The server can safely close in response to an EOF from the client, however it will also need to set a timeout when it is expecting an EOF in case the client has left the network ungracefully. In many cases simply waiting a few seconds before the server closes will be adequate.

I also advice you to learn more about networking and network programming. You should now at least how tcp protocol works. The protocol is quite trivial and small and hence, may save you a lot of time in future.

With netstat command you can easily see which programs ( (program_name,pid) tuple) are binded to which ports and what is the socket current state: TIME_WAIT, CLOSING, FIN_WAIT and so on.

Источник

Как побороть » address already in use»

Есть сферический код TCP-сервера на луа:

Подключаюсь к нему с помощью

Если развывать соединение, нажимая Ctrl+C в терминале с nc, то всё норм.

Если же разрывать соединение нажимая Ctrl+C в терминале с сервером, то его последующий запуск вываливается с ошибкой «address already in use» в строке с bind. Через минуту-две запускается нормально

Как побороть «address already in use»? Может подкрутить какие-то опции?

PS: сишников скастовал, потомучто только они разбираются в подобной низкоуровневой магии )

could not bind socket address and port are already in use как исправить

could not bind socket address and port are already in use как исправить

could not bind socket address and port are already in use как исправить

Вышеописанное поведение она не меняет. По-прежнему «address already in use» если тушить сервер при подключенном клиенте

could not bind socket address and port are already in use как исправить

SO_LINGER(с нулевым таймаутом)

could not bind socket address and port are already in use как исправить

could not bind socket address and port are already in use как исправить

reuseaddr влияет если сервер биндится к INADDR_ANY. Но т.к. сокет все-равно в полузакрытом состоянии, законектиться к тому же адресу и тому же порту не получится, пока ОС не отпустит сокет их состояния TIME_WAIT (60 сек, как показывает /proc/sys/net/ipv4/tcp_fin_timeout)

Собственно, переформулируя вопрос из ОП-поста: как повлиять на /proc/sys/net/ipv4/tcp_fin_timeout локально, только для моей програмы?

could not bind socket address and port are already in use как исправить

О, заработало! Спасибо)

could not bind socket address and port are already in use как исправить

убирать time_wait в ноль не очень красиво. навесь обработчик сигнала sigint и с нем рви соединение через tcp rst.

could not bind socket address and port are already in use как исправить

Некрасиво только если потом закрывать ненормально. А если в софте реализован graceful shutdown, то без linger вполне можно жить.

Если же разрывать соединение нажимая Ctrl+C в терминале с сервером

То можно зарегистрировать обработчик соответствующего сигнала. А в нём установить флаг is_shutdown. Теперь после ctrl-c будет вызван обработчик, потом server:accept завершится с ошибкой (EINTR), это можно словить и если флажок is_shutdown взведён, мы знаем, что всё ОК, пользователь хочет всё закрыть, закрываем и выходим

could not bind socket address and port are already in use как исправить

Оффтопик. А вне программы эту проблему можно решить?

Можно ли как-то принудительно очистить состояние порта?

could not bind socket address and port are already in use как исправить

could not bind socket address and port are already in use как исправить

could not bind socket address and port are already in use как исправить

убирать time_wait в ноль не очень красиво

навесь обработчик сигнала sigint и с нем рви соединение через tcp rst.

Пример был сферический. Sigint тоже. Скрипт нужен чтобы тестировать разрывы любимого ростелекома. А тут еще ядро свои разрывы добавляет)

could not bind socket address and port are already in use как исправить

пишу через обработчики уже 10 лет И НИ ЕДИНОГО РАЗРЫВА!!11

could not bind socket address and port are already in use как исправить

миллион способов, все зависит от того насколько «схаченное» решение для вас терпимо. можно сниффать сиквенс намбер и слать tcp rst, например из scapy (из удобного), или даже вроде есть специализированные утилиты. если все зависло так что траффика вообще никакого не проходит (ну, хотя бы кип-алайв зафорсить обычно можно — посылаешь со спуфленного адреса) то тогда можно подглядеть нужный сиквенс намбер прямо в ядре, например через systemtap или кастомным модулем. если же вопрос решается SO_LINGER с нулевым таймуатом, то можно его принудительно установить на сокет — пиши модуль для LD_PRELOAD с перехватом bind() например и устанавливай там дополнительные опции на сокет, я так для одного старого проприетарного говна увеличивал очередь необработанных коннектов.

could not bind socket address and port are already in use как исправить

Какой сигнал сработает когда ростелеком разорвет соединение?)

could not bind socket address and port are already in use как исправить

во-первых, если хочешь получить на свои топики нормальные рабочие ответы, давай в них всю информацию, а то сейчас еще выясниться что речь не про сервер TCP, а еще через две страницу — что и вовсе на самом деле у тебя там винда с SUA.

теперь по делу. если у тебя демон умирает когда говнотелеком рвет соединение, ты что-то делаешь не так. расскажи больше.

Источник

сервер рассылки :: Could not bind socket. Address and port are already

Официальный форум компании НАО «Сантэл-Навигация» → Сервера АРМ10 → сервер рассылки :: Could not bind socket. Address and port are already

Чтобы отправить ответ, вы должны войти или зарегистрироваться

Сообщений 4

1 Тема от nkz 01-09-2017 13:55:39

Тема: сервер рассылки :: Could not bind socket. Address and port are already

На одной машине установлены сервер и АРМ. На локальной машине АРМ работает. Никак не получается
подключиться удаленно: ни по сети (клиент на Win7), ни мобильно (клиент Андроид).

Звонили в службу поддержки, поковыряли в течение дня, сказали, что порт сервера рассылки занят чем-то и поэтому не возможно подключиться.

Сейчас переустановили систему Win7Prx64. Чистая, ничего не ставили. Поставили АРМ v.1.26 и сервер v.1.25.9. Все работает только на локальной машине. Клиенты опять не можем законнектить.

В логах сервера рассылки, если в Администраторе снята галка служба, показывает:

т.е. получается сервер рассылки активен

Если поставить галку Служба ВКЛ., то в логах пишет такое:

01.09 10:05:56 CS: Клиент: type = 7, url входа в систему: http://127.0.0.1:5551
01.09 10:05:56 CS: Сохранение времени и положения в параметрах тс включено
01.09 10:05:56 CS: http сервер не активен
01.09 10:05:56 CS: При активизации сервера вызвано исключение: Could not bind socket. Address and
port are already in use., порт по умолчанию 5552
01.09 10:05:56 CS: Binding1 port_min = 6199, port_max = 6100, port = 5552
01.09 10:05:56 CS: Порт по умолчанию 5552
01.09 10:05:56 CS: Инициализация http сервера

не может порт использовать:(

Скрин TCPView для состояния, когда все сервера запущены, АРМ работает, все отображается, машинки
ездят.
Судя по картинке сервер рассылки работает и висит на своем порту.

Куда еще поковырять?

Image 002.png 37.02 Кб, файл не был скачан.

You don’t have the permssions to download the attachments of this post.

Источник

Написал элементарные сервер и клиент на C. Всё работает, но есть одна небольшая проблема. Если соединение первым завершает сервер, то при повторном его запуске bind выдаёт ошибку:
bind: Address already in use
И так примерно минуту при каждой попытке запуска сервера bind выдаёт такую ошибку. По истечении минуты, сервер запускается без ошибок и всё опять работает нормально.
Если соединение завершает клиент, то при повторном запуске сервера ошибок не возникает.

Знающие люди, подскажите пожалуйста, в чём причина такого поведения и как сделать так, чтобы не нужно было ждать перед повторным запуском сервера.

could not bind socket address and port are already in use как исправить

could not bind socket address and port are already in use как исправить

Может вы некорректно закрываете соединение?

could not bind socket address and port are already in use как исправить

>Может вы некорректно закрываете соединение?

Может быть, хотя я в этом сомневаюсь.

could not bind socket address and port are already in use как исправить

а зачем сервер перезапускать вообще?

делается так:
0. открыли/завязали/etc сокет (socket, bind, listen)
1. получили входящее подключение (accept) и его файловый дескриптор
2. обработали (read, write)
3. закрыли файловый дескриптор соединения (close)
4. если не конец работы сервера, goto 1
5. закрыли сокет (close)

пункты 1-4 можно сделать (и обычно делают) многопоточными (а можно и гланды через select)

could not bind socket address and port are already in use как исправить

>а зачем сервер перезапускать вообще?

Это я понимаю. Дело не в том зачем перезапускать. Во-первых интересно почему так происходит. Во-вторых при отладке приходится минуту ждать. А в-третьих под виндой вроде такого нету.

could not bind socket address and port are already in use как исправить

>а зачем сервер перезапускать вообще?

Это я понимаю. Дело не в том зачем перезапускать. Во-первых интересно почему так происходит. Во-вторых при отладке приходится минуту ждать. А в-третьих под виндой вроде такого нету.

could not bind socket address and port are already in use как исправить

could not bind socket address and port are already in use как исправить

Добавил вызов setsockopt, теперь задержки нету. Спасибо! Пойду изучать что делает setsockopt 🙂

Кстати, разве обязательно вызывать shutdown?

Там ничего про обязательный вызов shutdown не написано.

could not bind socket address and port are already in use как исправить

could not bind socket address and port are already in use как исправить

could not bind socket address and port are already in use как исправить

читаем внмательно Стивенса

could not bind socket address and port are already in use как исправить

Про reuseaddr в каждой книжке по сетевому программированию говорится.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *