0

I'm trying to set up a socket for p2p communication. A I found this code, but I'm having a hard time understanding the code. What does SOL_SOCKET, as well as SOL_REUSE?

Could someone help me go through this code?

#!/usr/bin/env python
import socket, sys

self_broken = False

def wait(c):
    print('waiting...')
    c.send('waiting')
    broken = True
    while broken:
        status = c.recv(1024)
        if status == 'working':
            print(status)
            if self_broken:
                c.send('broken')
            else:
                c.send('starting')
                broken = False
    c.close()

def main():
    s = socket.socket()
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    host, port = socket.gethostname(), 10001
    s.bind((host, port))
    s.listen(1)
    while True:
        c, addr = s.accept()
        status = c.recv(1024)
        print(addr[0] + ':' + str(addr[1]) + ' > ' + status)
        if status == 'broken':
            wait(c)
        else:
            print(status)
        c.close()
    s.close()

main()

I found this explanation, but it is for C, does it apply for Python as well? This is for C, is it the same for Python?

EDIT: Can anyone tell med what the 'c' does? it's in wait(c), c.send and c.close.

Erik
  • 23
  • 1
  • 9
  • Yes, it's the same. When it comes to system level stuff, Python tries to provide only a thin wrapper around the system APIs. So much of what is available in man pages applies. The one thing that is a little different is the mechanics of actually setting the option--there's usually some adaptations when structures are being passed to system APIs--so it's good to look at the relevant Python docs too. – John Szakmeister Apr 30 '18 at 09:07
  • You're treading into territory that isn't relevant for Stack Overflow. See [How to Ask](https://stackoverflow.com/help/how-to-ask) and [What can I ask about here?](https://stackoverflow.com/help/on-topic). You can see the definition of `wait()` in the code there. Why it does what it does? I don't know. It seems kind strange to me. While `self_broken` is False, it sends `"starting"` in response to whatever it receives (which is done poorly, IMHO). If `self_broken` is True, it'll always send `"broken"` and never stops because no one will set it back to False. – John Szakmeister Apr 30 '18 at 12:46
  • The other two, `c.close()` and `c.send()` are socket/file descriptor operations. The first closes the socket. The latter will send data across the socket. As I said though, this isn't really good form for a network protocol. There doesn't seem to be any message delimiters and you're relying on data being delivered as whole units--which is not guaranteed since TCP is a streaming interface, not a message-oriented one. Oh, I see that you were actually asking about `c` versus the actual routines. `c` is the accepted socket connection and it's being passed to wait so that it can use it. – John Szakmeister Apr 30 '18 at 12:49

0 Answers0