Search code examples
c#pythonsocketstcp

Why does my python TCP server need to bind to 0.0.0.0 and not localhost or it's IP address?


I'm making a Python TCP server and a C# client, and I got it to work, but I don't understand why it's working and I'm hoping someone can explain to me what I'm missing. I'm trying to connect from within my own network, so there are no firewalls involved.

In my python script, if I bind to 127.0.0.1 or localhost I cannot connect to it from my C# script, so I thought maybe it needs to be the local IP address that the DHCP server gives it, so I tried binding to 192.168.1.74 (the local IP address). That still didn't work, however if I use 0.0.0.0 as the port I bind to, I am able to connect without a problem.

Python Server Code:

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 Code:

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();
}

Why does it only work with 0.0.0.0?

EDIT: After binding to 0.0.0.0 and connecting, I can now bind to it's IP address (192.168.1.74) and connect. Though 0.0.0.0 allows me to connect via localhost and 127.0.0.1 so I think I'll keep using it.


Solution

  • 127.0.0.1 and localhost (which are basically the same), are 'local loopback' addresses. This means that they can only be accessed from your computer. Any other computer (even on your own network) cannot connect to them. This might also also depend on your operating system.

    To be able to connect to the server within your own network, I think you can use 0.0.0.0, or your local IP address. You can find it in Windows with ipconfig, and in Linux (I think in MAC too) with ifconfig. It will most likely look something like "192.168.a.b", but that depends a bit on the configuration of your network.