为什么我的python TCP服务器需要绑定到0.0.0.0而不是localhost或它的IP地址?

时间:2016-07-07 23:33:05

标签: c# python sockets tcp

我正在制作一个Python TCP服务器和一个C#客户端,我让它工作,但我不明白为什么它正在工作,我希望有人可以向我解释一下我迷路了。我正在尝试从我自己的网络内部进行连接,因此不涉及防火墙。

在我的python脚本中,如果我绑定到127.0.0.1localhost我无法从我的C#脚本连接到它,所以我想也许它需要是DHCP服务器提供的本地IP地址它,所以我尝试绑定到192.168.1.74(本地IP地址)。这仍然无效,然而如果我使用0.0.0.0作为我绑定的端口,我能够连接没有问题。

Python服务器代码:

def startserver():
    global serversocket
    global server

    serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    serversocket.bind(('0.0.0.0', 8089))
    #limit connections to 1 because we only expect C# code to talk to us
    serversocket.listen(1)
    print("Server Started, await connections...")

C#TCPclient代码:

public string host = "192.168.1.74";
public int port = 8089;

public void ConnectSocket(string server, int port)
{
    TcpClient client = new TcpClient(server, port);

    byte[] data = System.Text.Encoding.ASCII.GetBytes("Hello World");

    NetworkStream stream = client.GetStream();

    stream.Write(data, 0, data.Length);

    print(string.Format("Sent: {0}", "Hellow World"));
    data = new byte[256];

    string responseData = string.Empty;

    int bytes = stream.Read(data, 0, data.Length);
    responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
    print(string.Format("Received: {0}", responseData));

    stream.Close();
    client.Close();
}

为什么它只适用于0.0.0.0

编辑:绑定到0.0.0.0并连接后,我现在可以绑定到它的IP地址(192.168.1.74)并连接。虽然0.0.0.0允许我通过localhost127.0.0.1进行连接,但我认为我会继续使用它。

1 个答案:

答案 0 :(得分:5)

127.0.0.1和localhost(基本相同)是本地环回'地址。这意味着只能从您的计算机访问它们。任何其他计算机(即使在您自己的网络上)也无法连接到它们。这也可能还取决于您的操作系统。

为了能够连接到您自己网络中的服务器,我认为您可以使用0.0.0.0或您的本地IP地址。您可以在Windows中使用ipconfig找到它,在Linux中(我也认为在MAC中也可以)使用ifconfig。它很可能看起来像" 192.168.a.b",但这取决于你的网络配置。

相关问题