0

I created a code that allows me to connect to a html page and print my Data there but the problem that everytime I execute the code I'm obliged to change this ports.bind("","80) manuelly because after I try to stop the code the port still running (In use) So I change to another values in order to execute my code

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 80))
s.listen(5)
while True:
 conn, addr = s.accept()
 print('Got a connection from %s' % str(addr))
  request = conn.recv(1024)
  request = str(request)
  print('Content = %s' % request)
  led_on = request.find('/?led=on')
  led_off = request.find('/?led=off')
   response =""
    if led_on == 6:
     print('LED ON')
     led.value(1)
    if led_off == 6:
     i2c= I2C ( scl = Pin(5) , sda = Pin(4))
     acc = mpu.accel(i2c)
     r = accelerometer.get_values()
  result.append(r)
  if len(result) > 8:
      result =  result[1:]
 #    print(str(r))
      print('LED OFF')
      led.value(0)
  response = web_page()
  conn.send('HTTP/1.1 200 OK\n')
  conn.send('Content-Type: text/html\n')
  conn.send('Connection: close\n\n')
  conn.sendall(response)
  conn.close()

Any Idea on preventing this ?

  • Check https://stackoverflow.com/questions/2942721/on-linux-how-to-check-if-port-is-in-listen-state-without-trying-to-connect to see if they are actually in listen state. Also do they free up after some time? There is a delay sometimes in some OS's freeing the port for use again. There should be some process listed as running & listening on those ports via `netstat`. – Catalyst Feb 23 '19 at 20:28
  • 1
    @Catalyst thank you , I'm checking it :) –  Feb 23 '19 at 20:36

1 Answers1

0

Any Idea on preventing this ?

Before you .bind(), you want to set this option:

s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)

It relaxes some timing enforcement performed by the kernel's TCP layer, which you will find convenient during development and debugging. Once the code is stable and released in production, it restarts less often so the timing is less of an issue.

With the current code, just after CTRL/C you should see your port 80 socket in TIME_WAIT state for a while. Until the timer expires, no application will be able to listen on 80. After setting the socket option the socket will quickly be recycled to allow a new application process to listen on 80.

Warren Young was kind enough to explain the motivation behind this TCP design choice in What is the meaning of SO_REUSEADDR (setsockopt option) - Linux?

J_H
  • 17,926
  • 4
  • 24
  • 44