为什么我要绑定到与 127.0.0.1 不同的服务器上? [英] Why would I bind on a different server than 127.0.0.1?

查看:84
本文介绍了为什么我要绑定到与 127.0.0.1 不同的服务器上?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始用 Python 学习网络".我已经按照基本教程运行带有 TCP 连接的客户端/服务器架构.我明白了整个逻辑,但我不明白为什么我会将我的服务器绑定到 127.0.0.1 以外的另一台主机上?我的意思是,我的服务器程序应该在接收请求的服务器上运行.是否有将服务器套接字绑定到 127.0.0.1 以外的其他地方的情况?

I am starting to learn 'networking' with Python. I have followed a basic tutorial to run a Client/Server architecture with a TCP connection. I get the whole logic, but I don't understand why I would bind my server on another host than 127.0.0.1? I mean, my server program should run on the server that receives the request. Are there case where it is useful to bind the server socket on something else than 127.0.0.1?

以下是客户端和服务器程序:

Here are the Client and Server programs:

** 服务器 **

import socket

def main():
    host = '127.0.0.1'
    port = 5000
    s = socket.socket()
    s.bind((host, port))
    s.listen(1)
    c, addr = s.accept()
    print('Connection from: ' + str(addr))
    while True:
        data = c.recv(1024).decode('utf-8')
        if not data:
            break
        print('From connected user: ' + data)
        data = data.upper()
        print('Sending ' + data)
        c.send(data.encode('utf-8'))
    c.close()

if __name__ == '__main__':
    main()

** 客户 **

import socket

def main():
    host = '127.0.0.1'
    port = 5000
    s = socket.socket()
    s.connect((host, port))
    msg = input('> ')
    while msg != 'q':
        s.send(msg.encode('utf-8'))
        data = s.recv(1024).decode('utf-8')
        print('Received from server: ' + data)
        msg = input('> ')
    s.close()

if __name__ == '__main__':
    main()

推荐答案

您不绑定到机器,而是绑定到网络接口,因此您希望绑定到将接收传入数据包的接口.例如,127.0.0.1 是内部(循环)接口,在同一台机器之外的任何地方都无法访问,因此您希望在期望来自外部的流量时立即绑定到不同的接口.

You don't bind to a machine but to a network interface, so you want to bind to the interface that will receive the incoming packets. For example, 127.0.0.1 is the internal (loop) interface that is not reachable from anywhere outside the same machine, so you want to bind to a different interface as soon as you expect traffic from outside.

主机可以有任意数量的网络接口,例如通过使用多个 LAN 适配器、同时使用 LAN 和无线,或者由于虚拟化.您可能只想收听特定界面,可能是为了限制对您的无线网络的访问,但没有其他原因,或者您可能有任何原因.

A host can have any number of network interfaces, for example by using multiple LAN adapters, using LAN and Wireless at the same time, or due to virtualisation. You may want to listen to a specific interface only, maybe in order to restrict accessibility to your wireless network but no other, or whatever reason you may have.

绑定到 0.0.0.0 将使您的进程同时侦听所有可用接口.

Binding to 0.0.0.0 will make your process listen to all available interfaces at the same time.

这篇关于为什么我要绑定到与 127.0.0.1 不同的服务器上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆