标签归档:port

在localhost上,如何选择空闲端口号?

问题:在localhost上,如何选择空闲端口号?

我正在尝试进行进程间通信,并且由于无法弄清楚如何在Windows下使用命名管道,因此我认为我将使用网络套接字。一切都发生在本地。服务器能够在单独的进程中启动从属服务器,并在某些端口上进行侦听。奴隶完成工作并将结果提交给主人。如何确定哪个端口可用?我假设我无法在端口80或21上收听?

我正在使用Python,如果这样做会减少选择的余地。

谢谢!

I’m trying to play with inter-process communication and since I could not figure out how to use named pipes under Windows I thought I’ll use network sockets. Everything happens locally. The server is able to launch slaves in a separate process and listens on some port. The slaves do their work and submit the result to the master. How do I figure out which port is available? I assume I cannot listen on port 80 or 21?

I’m using Python, if that cuts the choices down.

Thanks!


回答 0

不要绑定到特定端口,也不要绑定到端口0,例如sock.bind(('', 0))。然后,操作系统将为您选择一个可用端口。您可以使用来获得选择的端口sock.getsockname()[1],并将其传递给从站,以便它们可以重新连接。

Do not bind to a specific port, or bind to port 0, e.g. sock.bind(('', 0)). The OS will then pick an available port for you. You can get the port that was chosen using sock.getsockname()[1], and pass it on to the slaves so that they can connect back.


回答 1

为了简要说明上面的解释:

import socket
from contextlib import closing

def find_free_port():
    with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s:
        s.bind(('', 0))
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        return s.getsockname()[1]

For the sake of snippet of what the guys have explained above:

import socket
from contextlib import closing

def find_free_port():
    with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s:
        s.bind(('', 0))
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        return s.getsockname()[1]

回答 2

将套接字绑定到端口0。将选择一个从1024到65535的随机空闲端口。您可以在getsockname()之后紧跟着检索选定的端口bind()

Bind the socket to port 0. A random free port from 1024 to 65535 will be selected. You may retrieve the selected port with getsockname() right after bind().


回答 3

您可以在任何端口上侦听;通常,用户应用程序应侦听端口1024及更高端口(通过65535)。如果您的侦听器数量可变,那么最主要的事情就是为您的应用分配一个范围-例如20000-21000和CATCH EXCEPTIONS。这样,您将知道计算机上端口是否不可用(换句话说,由另一个进程使用)。

但是,就您而言,只要绑定失败时打印错误消息,就可以为侦听器使用单个硬编码端口,这不会有问题。

还要注意,您的大多数套接字(用于从属)不需要显式绑定到特定的端口号-仅需要将等待传入连接的套接字(例如此处的主机)设置为侦听器并绑定到端口。如果在使用套接字之前未为端口指定端口,则操作系统将为该套接字分配可用端口。当主机希望响应从机发送数据时,当侦听器接收数据时,可以访问发送者的地址。

我想您将为此使用UDP?

You can listen on whatever port you want; generally, user applications should listen to ports 1024 and above (through 65535). The main thing if you have a variable number of listeners is to allocate a range to your app – say 20000-21000, and CATCH EXCEPTIONS. That is how you will know if a port is unusable (used by another process, in other words) on your computer.

However, in your case, you shouldn’t have a problem using a single hard-coded port for your listener, as long as you print an error message if the bind fails.

Note also that most of your sockets (for the slaves) do not need to be explicitly bound to specific port numbers – only sockets that wait for incoming connections (like your master here) will need to be made a listener and bound to a port. If a port is not specified for a socket before it is used, the OS will assign a useable port to the socket. When the master wants to respond to a slave that sends it data, the address of the sender is accessible when the listener receives data.

I presume you will be using UDP for this?


回答 4

如果您只需要找到一个空闲端口供以后使用,这是一个类似于先前答案的代码段,但使用socketserver则更短:

import socketserver

with socketserver.TCPServer(("localhost", 0), None) as s:
    free_port = s.server_address[1]

请注意,不能保证端口保持空闲状态,因此您可能需要将此代码段和使用它的代码放入循环中。

If you only need to find a free port for later use, here is a snippet similar to a previous answer, but shorter, using socketserver:

import socketserver

with socketserver.TCPServer(("localhost", 0), None) as s:
    free_port = s.server_address[1]

Note that the port is not guaranteed to remain free, so you may need to put this snippet and the code using it in a loop.


如何使Flask在端口80上运行?

问题:如何使Flask在端口80上运行?

我有一个通过端口5000运行的Flask服务器,很好。我可以在http://example.com:5000上访问它

但是是否可以在http://example.com上简单地访问它?我假设这意味着我必须将端口从5000更改为80。但是当我在Flask上尝试该端口时,运行该错误消息。

Traceback (most recent call last):
  File "xxxxxx.py", line 31, in <module>
app.run(host="0.0.0.0", port=int("80"), debug=True)
   File "/usr/local/lib/python2.6/dist-packages/flask/app.py", line 772, in run
run_simple(host, port, self, **options)
  File "/usr/local/lib/python2.6/dist-packages/werkzeug/serving.py", line 706, in run_simple
    test_socket.bind((hostname, port))
  File "<string>", line 1, in bind
socket.error: [Errno 98] Address already in use

连续lsof -i :80收益

COMMAND   PID     USER   FD   TYPE   DEVICE SIZE/OFF NODE NAME
apache2   467     root    3u  IPv4 92108840      0t0  TCP *:www (LISTEN)
apache2  4413 www-data    3u  IPv4 92108840      0t0  TCP *:www (LISTEN)
apache2 14346 www-data    3u  IPv4 92108840      0t0  TCP *:www (LISTEN)
apache2 14570 www-data    3u  IPv4 92108840      0t0  TCP *:www (LISTEN)
apache2 14571 www-data    3u  IPv4 92108840      0t0  TCP *:www (LISTEN)
apache2 14573 www-data    3u  IPv4 92108840      0t0  TCP *:www (LISTEN)

我需要先杀死这些进程吗?这样安全吗?还是有另一种方法可以使Flask在端口5000上运行,但是使主网站域以某种方式重定向?

I have a Flask server running through port 5000, and it’s fine. I can access it at http://example.com:5000

But is it possible to simply access it at http://example.com? I’m assuming that means I have to change the port from 5000 to 80. But when I try that on Flask, I get this error message when I run it.

Traceback (most recent call last):
  File "xxxxxx.py", line 31, in <module>
app.run(host="0.0.0.0", port=int("80"), debug=True)
   File "/usr/local/lib/python2.6/dist-packages/flask/app.py", line 772, in run
run_simple(host, port, self, **options)
  File "/usr/local/lib/python2.6/dist-packages/werkzeug/serving.py", line 706, in run_simple
    test_socket.bind((hostname, port))
  File "<string>", line 1, in bind
socket.error: [Errno 98] Address already in use

Running lsof -i :80 returns

COMMAND   PID     USER   FD   TYPE   DEVICE SIZE/OFF NODE NAME
apache2   467     root    3u  IPv4 92108840      0t0  TCP *:www (LISTEN)
apache2  4413 www-data    3u  IPv4 92108840      0t0  TCP *:www (LISTEN)
apache2 14346 www-data    3u  IPv4 92108840      0t0  TCP *:www (LISTEN)
apache2 14570 www-data    3u  IPv4 92108840      0t0  TCP *:www (LISTEN)
apache2 14571 www-data    3u  IPv4 92108840      0t0  TCP *:www (LISTEN)
apache2 14573 www-data    3u  IPv4 92108840      0t0  TCP *:www (LISTEN)

Do I need to kill these processes first? Is that safe? Or is there another way to keep Flask running on port 5000 but have the main website domain redirect somehow?


回答 0

因此,由于您已经apache2在端口80上运行,因此抛出了该错误消息。

如果这是为了开发,我将其保留在端口5000上。

如果用于生产:

不建议

  • apache2先停下来

不建议使用,因为它在文档中指出:

您可以在开发过程中使用内置服务器,但应该对生产应用程序使用完整的部署选项。(请勿在生产中使用内置的开发服务器。)

推荐的

  • 代理 HTTP通过apache2访问Flask。

这条路, apache2就可以处理所有静态文件(非常擅长-比Flask内置的调试服务器要好得多),并充当动态内容的反向代理,将这些请求传递给Flask。

这是一个链接有关使用Apache + mod_wsgi设置Flask的官方文档。

编辑1-澄清@Djack

通过apache2到Flask的代理HTTP流量

当请求通过端口80(HTTP)或端口443(HTTPS)到达服务器时,类似Apache或Nginx的Web服务器将处理请求的连接并确定如何处理该请求。在我们的情况下,应该将收到的请求配置为通过WSGI协议传递给Flask并由Python代码处理。这是“动态”部分。

动态内容的反向代理

像上面那样配置Web服务器有一些好处;

  • SSL终端-仅需少量配置即可优化Web服务器以处理HTTPS请求。相比之下,不要在Python中“自己动手”。
  • 安全性-打开Internet端口需要仔细考虑安全性。Flask的开发服务器不是为此目的而设计的,与为此目的设计的Web服务器相比,它可能存在开放的错误或安全问题。请注意,配置错误的Web服务器也可能不安全!
  • 静态文件处理-内置的Flask Web服务器可以处理静态文件,但是不建议这样做。Nginx / Apache在处理静态文件(如图像,CSS,Javascript文件)方面效率更高,并且仅传递“动态”请求(那些内容通常是从数据库中读取或内容发生更改的请求)以由Python代码处理。
  • +更多。这接近于该问题的范围。如果您想了解更多信息,请对该领域进行一些研究。

So it’s throwing up that error message because you have apache2 running on port 80.

If this is for development, I would just leave it as it is on port 5000.

If it’s for production either:

Not Recommended

  • Stop apache2 first;

Not recommended as it states in the documentation:

You can use the builtin server during development, but you should use a full deployment option for production applications. (Do not use the builtin development server in production.)

Recommended

  • Proxy HTTP traffic through apache2 to Flask.

This way, apache2 can handle all your static files (which it’s very good at – much better than the debug server built into Flask) and act as a reverse proxy for your dynamic content, passing those requests to Flask.

Here’s a link to the official documentation about setting up Flask with Apache + mod_wsgi.

Edit 1 – Clarification for @Djack

Proxy HTTP traffic to Flask through apache2

When a request comes to the server on port 80 (HTTP) or port 443 (HTTPS) a web server like Apache or Nginx handles the connection of the request and works out what to do with it. In our case a request received should be configured to be passed through to Flask on the WSGI protocol and handled by the Python code. This is the “dynamic” part.

reverse proxy for dynamic content

There are a few advantages to configuring your web server like the above;

  • SSL Termination – The web server will be optimized to handle HTTPS requests with only a little configuration. Don’t “roll your own” in Python which is probably very insecure in comparison.
  • Security – Opening a port to the internet requires careful consideration of security. Flask’s development server is not designed for this and could have open bugs or security issues in comparison to a web server designed for this purpose. Note that a badly configured web server can also be insecure!
  • Static File Handling – It is possible for the builtin Flask web server to handle static files however this is not recommended; Nginx/Apache are much more efficient at handling static files like images, CSS, Javascript files and will only pass “dynamic” requests (those where the content is often read from a database or the content changes) to be handled by the Python code.
  • +more. This is bordering on scope for this question. If you want more info do some research into this area.

回答 1

1-停止使用端口80的其他应用程序。2-使用端口80运行应用程序:

if __name__ == '__main__':
      app.run(host='0.0.0.0', port=80)

1- Stop other applications that are using port 80. 2- run application with port 80 :

if __name__ == '__main__':
      app.run(host='0.0.0.0', port=80)

回答 2

对于外部可见的服务器,您不使用apache或其他Web服务器,只需键入

flask run --host=0.0.0.0 --port=80

For externally visible server, where you don’t use apache or other web server you just type

flask run --host=0.0.0.0 --port=80

回答 3

如果使用以下命令更改端口或主机:

if __name__ == '__main__':
  app.run(host='0.0.0.0', port=80)

使用以下代码启动服务器(我的flask的主入口是app.py):

python app.py

而不是使用:

flask run

If you use the following to change the port or host:

if __name__ == '__main__':
  app.run(host='0.0.0.0', port=80)

use the following code to start the server (my main entrance for flask is app.py):

python app.py

instead of using:

flask run

回答 4

如果要将应用程序放在相同的端口(即port = 5000)上,则只需在终端中运行以下命令:

fuser -k 5000/tcp

然后运行:

python app.py

如果要在指定端口上运行,例如,如果要在port = 80上运行,请在主文件中提及:

if __name__ == '__main__':  
    app.run(host='0.0.0.0', port=80)

If you want your application on same port i.e port=5000 then just in your terminal run this command:

fuser -k 5000/tcp

and then run:

python app.py

If you want to run on a specified port, e.g. if you want to run on port=80, in your main file just mention this:

if __name__ == '__main__':  
    app.run(host='0.0.0.0', port=80)

回答 5

一种方便的方式是使用软件包python-dotenv:它读取一个.flaskenv文件,您可以在其中存储flask的环境变量。

  • pip install python-dotenv
  • .flaskenv在应用程序的根目录中创建文件

在您指定的文件内:

FLASK_APP=application.py
FLASK_RUN_HOST=localhost
FLASK_RUN_PORT=80

之后,您只需要运行 flask run即可在该端口访问您的应用程序。

请注意,FLASK_RUN_HOST默认为127.0.0.1FLASK_RUN_PORT默认为5000

A convinient way is using the package python-dotenv: It reads out a .flaskenv file where you can store environment variables for flask.

  • pip install python-dotenv
  • create a file .flaskenv in the root directory of your app

Inside the file you specify:

FLASK_APP=application.py
FLASK_RUN_HOST=localhost
FLASK_RUN_PORT=80

After that you just have to run your app with flask run and can access your app at that port.

Please note that FLASK_RUN_HOST defaults to 127.0.0.1 and FLASK_RUN_PORT defaults to 5000.


回答 6

这是在Ubuntu-18上对我有用的唯一解决方案。

在文件中app.py,使用:

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=80)

除非sudo用于运行它,否则上面的代码将给出相同的权限错误:

sudo python3 app.py

This is the only solution that worked for me on Ubuntu-18.

Inside the file app.py , use:

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=80)

The code above will give the same permission error unless sudo is used to run it:

sudo python3 app.py

回答 7

您的问题是,已经有一个正在使用端口80的apache网络服务器正在运行。因此,您可以:

  1. 杀死apache:您可能应该通过这样做/etc/init.d/apache2 stop,而不是简单地杀死它们。

  2. 如apache中的flask所述,在apache进程中部署flask应用程序。

Your issue is, that you have an apache webserver already running that is already using port 80. So, you can either:

  1. Kill apache: You should probably do this via /etc/init.d/apache2 stop, rather than simply killing them.

  2. Deploy your flask app in your apache process, as flask in apache describes.


回答 8

我必须FLASK_RUN_PORT在我的环境中将其设置为指定的端口号。下次启动应用程序时,Flask将使用您选择的端口号加载该环境变量。

I had to set FLASK_RUN_PORT in my environment to the specified port number. Next time you start your app, Flask will load that environment variable with the port number you selected.


回答 9

您无需更改应用程序的端口号,只需配置www服务器(nginx或apache)即可将查询代理到flask端口。支付的减免费用uWSGI

You don’t need to change port number for your application, just configure your www server (nginx or apache) to proxy queries to flask port. Pay attantion on uWSGI.


回答 10

设置端口,app.run(port=80,debug=True) 在开发时应将debug设置为true

set the port with app.run(port=80,debug=True) you should set debug to true when on dev


回答 11

最简单,最好的解决方案

将.py文件保存在文件夹中。这种情况下我的文件夹名称是test。在命令提示符下运行以下命令

c:\test> set FLASK_APP=application.py
c:\test> set FLASK_RUN_PORT=8000
c:\test> flask run

—————–将返回以下—————-

 * Serving Flask app "application.py"
 * Environment: production
   WARNING: Do not use the development server in a production environment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on http://127.0.0.1:8000/ (Press CTRL+C to quit)
127.0.0.1 - - [23/Aug/2019 09:40:04] "[37mGET / HTTP/1.1[0m" 200 -
127.0.0.1 - - [23/Aug/2019 09:40:04] "[33mGET /favicon.ico HTTP/1.1[0m" 404 -

现在,在浏览器上输入:http : //127.0.0.1 : 8000。谢谢

Easiest and Best Solution

Save your .py file in a folder. This case my folder name is test. In the command prompt run the following

c:\test> set FLASK_APP=application.py
c:\test> set FLASK_RUN_PORT=8000
c:\test> flask run

—————– Following will be returned —————-

 * Serving Flask app "application.py"
 * Environment: production
   WARNING: Do not use the development server in a production environment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on http://127.0.0.1:8000/ (Press CTRL+C to quit)
127.0.0.1 - - [23/Aug/2019 09:40:04] "[37mGET / HTTP/1.1[0m" 200 -
127.0.0.1 - - [23/Aug/2019 09:40:04] "[33mGET /favicon.ico HTTP/1.1[0m" 404 -

Now on your browser type: http://127.0.0.1:8000. Thanks


回答 12

在我的方案中,以下步骤非常有用:

  • 安装软件包:

    pip install --upgrade pip
    pip install python-dotenv
  • 在我的应用程序目录“ flaskr / .flaskenv”中创建隐藏文件

  • 添加以下内容:

    FLASK_APP=flaskr
    FLASK_RUN_HOST=localhost
    FLASK_RUN_PORT=8000
  • 最后,再次运行flask命令:

    flask run
  • 我正在处理的版本是:

    pip freeze |grep -i flask
    Flask==1.1.1

On my scenario the following steps worked like a charm:

  • Installing the package:

    pip install --upgrade pip
    pip install python-dotenv
    
  • Creating a hidden file in my app directory “flaskr/.flaskenv”

  • Adding the following content:

    FLASK_APP=flaskr
    FLASK_RUN_HOST=localhost
    FLASK_RUN_PORT=8000
    
  • Finally, run the flask command one more time:

    flask run
    
  • The version which I am working on is:

    pip freeze |grep -i flask
    Flask==1.1.1