Cannot bind 127.0.0.123 to tcp socket python I'm trying to learn TCP sockets for my project. I will be using them to transfer files between computers.

The server client combo copied from some tutorial runs fine as long, as the ip I'm trying to bound is 127.0.0.1. When I change it to anything less standard, like 127.0.0.123 OSX says, that I cannot bind to this address:
socket.error: [Errno 49] Can't assign requested address  

I have no problems on debian tough.  

Server code   

#!/usr/bin/env python

import socket

TCP_IP = '127.0.0.123'
TCP_PORT = 50050
BUFFER_SIZE = 1024  # Normally 1024, but we want fast response

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((TCP_IP, TCP_PORT))
s.listen(1)

conn, addr = s.accept()
print 'Connection address:', addr
while 1:
    data = conn.recv(BUFFER_SIZE)
    if not data: break
    print "received data:", data
    conn.send(data)  # echo
conn.close()


Client code:

#!/usr/bin/env python

import socket


TCP_IP = '127.0.0.123'
TCP_PORT = 50050
BUFFER_SIZE = 1024
MESSAGE = "message sent from client to server"

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
s.send(MESSAGE)
s.close()
On a Mac the loopback interface only has the 127.0.0.1 address configured. You could always add an alias to the IP you need:

sudo ifconfig lo0 alias 127.0.0.123


Your python code worked for me then.

To delete the alias do the following:

sudo ifconfig lo0 -alias 127.0.0.123




To make this persistent over reboots create org.local.localhost.plist in /Library/LaunchDaemons/. 
Change the permissions with: 

sudo chmod root:wheel /Library/LaunchDaemons/org.local.localhost.plist


Open the file with 

sudo nano /Library/LaunchDaemons/org.local.localhost.plist


and add the following content:

&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"&gt;
&lt;plist version="1.0"&gt;
&lt;dict&gt;
    &lt;key&gt;Label&lt;/key&gt;
    &lt;string&gt;org.local.localhost&lt;/string&gt;
    &lt;key&gt;ProgramArguments&lt;/key&gt;
    &lt;array&gt;
        &lt;string&gt;/sbin/ifconfig&lt;/string&gt;
        &lt;string&gt;lo0&lt;/string&gt;
        &lt;string&gt;alias&lt;/string&gt;
        &lt;string&gt;127.0.0.123&lt;/string&gt;
        &lt;string&gt;up&lt;/string&gt;
    &lt;/array&gt;
    &lt;key&gt;RunAtLoad&lt;/key&gt;
    &lt;true/&gt;
&lt;/dict&gt;
&lt;/plist&gt;


Finally load the launch daemon with:

sudo launchctl load /Library/LaunchDaemons/org.local.localhost.plist