MarAja
MarAja

Reputation: 1597

Why would I bind on a different server than 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:

** Server **

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

** Client **

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

Upvotes: 1

Views: 879

Answers (2)

ForceBru
ForceBru

Reputation: 44838

You can bind to 192.168.1.5, or whatever your local IP address is so your server is reachable from the local network.

You can also bind to 104.31.82.58, or whatever your public IP is so anyone from all over the world could connect to your server.

I mean, you can't really bind to 104.31.82.58, you should bind to your own IP address.

Upvotes: 0

Thomas Lotze
Thomas Lotze

Reputation: 5313

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.

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.

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

Upvotes: 6

Related Questions