如何在 python 中创建一个简单的 DNS 服务器同时监听两个端口

发布于 2024-08-11 03:56:52 字数 819 浏览 4 评论 0原文

我正在尝试用 python 构建 DNS 服务器。它必须侦听两个端口(8007 - 客户端,80​​08 - 管理)。客户端仅发送 URL 并接收相应的 IP。管理员有权更改 DNS 表(添加、删除……现在与此无关)。

所以我的问题是:如何实现服务器在两个端口上连续监听任何最终请求(我们可以同时有多个客户端,但在操作时只有一个管理员)

我的服务器只有一个监听端口:

from SocketServer import * 从线程导入* 从字符串导入 * 进口插座

    class Server(ForkingMixIn, TCPServer): pass  #fork for each client

    class Handler(StreamRequestHandler):

        def handle(self):
            addr = self.request.getpeername()
            print 'Got connection from', addr
            data=(self.request.recv(1024)).strip()

            if data not in dic: #dic -> dictionary with URL:IP
                self.wfile.write('0.0.0.0')
            else:
                self.wfile.write(dic.get(data))


    server = Server(('', 8007), Handler)
    server.serve_forever()

I'm trying to build a DNS server in python. It must listen two ports (8007 - client, 8008 - admin). The client only send an URL and receives the respective IP. The admin has permissions to change the DNS table (add, remove,.. doesn't matter to this right now).

So my question is: how do I implement the server listening continuously on the two ports for any eventual request (we can have several clients at the same time but only one admin when he is operating)

my Server with one listening port:

from SocketServer import *
from threading import *
from string import *
import socket

    class Server(ForkingMixIn, TCPServer): pass  #fork for each client

    class Handler(StreamRequestHandler):

        def handle(self):
            addr = self.request.getpeername()
            print 'Got connection from', addr
            data=(self.request.recv(1024)).strip()

            if data not in dic: #dic -> dictionary with URL:IP
                self.wfile.write('0.0.0.0')
            else:
                self.wfile.write(dic.get(data))


    server = Server(('', 8007), Handler)
    server.serve_forever()

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

枫林﹌晚霞¤ 2024-08-18 03:56:52

无需使用线程。

使用扭曲。

TwistedNames 提供对 DNS 服务器的开箱即用支持。您可以根据需要对其进行自定义,或者在构建自己的源代码时将其源代码作为基础。

No need to use threads.

Use twisted.

TwistedNames has support out of the box for a dns server. You can customize it as needed or read its source as base when you build yours.

冷清清 2024-08-18 03:56:52

您可以使用非阻塞套接字,并使用 select 调用从套接字读取数据。这篇 Python 套接字编程指南 文章中有一个关于 Python 中的非阻塞套接字 会有所帮助。

另请参阅:

You can use non-blocking sockets, and use the select call to read from the socket. This Sockets Programming HOWTO for Python article has a section on non-blocking sockets in Python that will help.

See also:

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文