Search code examples
pythontunnel

python bind socket.error: [Errno 13] Permission denied


I have a python script which gets packets from a remote machine and writes them (os.write(self.tun_fd.fileno(), ''.join(packet))) to a tun interface gr3:

Link encap:UNSPEC  HWaddr 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00  
inet addr:10.0.0.6  P-t-P:10.0.0.8  Mask:255.255.255.255
UP POINTOPOINT RUNNING NOARP MULTICAST  MTU:1500  Metric:1
RX packets:61 errors:0 dropped:0 overruns:0 frame:0
TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:500 
RX bytes:5124 (5.0 KiB)  TX bytes:0 (0.0 b)

I would like to receive those packets via a separate pong script as follows:

import threading, os, sys, fcntl, struct, socket
from fcntl import ioctl
from packet import Packet

HOST = '10.0.0.6'
PORT = 111
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
    data = conn.recv(1024)
    if not data: break
    else: print data    
    conn.sendall(data)
conn.close()

I got this error :

s.bind((HOST, PORT))
File "<string>", line 1, in bind
socket.error: [Errno 13] Permission denied

Solution

  • You can't bind to port numbers lower than 1024 as a unprivileged user.

    So you should either:

    • Use a port number larger than 1024 (recommended)
    • Or run the script as a privileged user

    Harder, but more secure solution if it's really necessary to accept from 111:

    • Run the as unprivileged on a higher port, and forward port 111 to it externally.