Swapnil
Swapnil

Reputation: 9

I am getting socket connection error in python Socket server programming

I am creating a Honeypot project in python3. So I am using python3 socket and _thread library in order to accomplish my goal. Here is my code:

    import _thread
    import time
    from socket import socket,AF_INET,SOCK_STREAM
    
    
    
    def OpenPort23():
            while(1>0):
                    print("Telnet port opened on 23 port")
                    port=23
                    sk=socket(AF_INET,SOCK_STREAM)
                    sk.bind(('127.0.0.1',port))
                    sk.listen(5)
                    conn,addr = sk.accept()
                    print('alert '+addr[0]+' has connected with us on port '+str(port))
                    sk.close()
                    print("Telnet Port 23 closed")
                    time.sleep(3)
    
    
    
    
    
    try:
            _thread.start_new_thread(OpenPort23,())
    except:
            pass
    while 1:
            pass

So when i run the above script, the program is responding normal with nmap command as below:

    **Nmap Command: nmap localhost -p 23**

    ~/mypro $ sudo python3 port23.py 
    Telnet port opened on 23 port
    alert 127.0.0.1 has connected with us on port 23
    Telnet Port 23 closed
    Telnet port opened on 23 port
    alert 127.0.0.1 has connected with us on port 23
    Telnet Port 23 closed
    Telnet port opened on 23 port
    alert 127.0.0.1 has connected with us on port 23
    Telnet Port 23 closed
    Telnet port opened on 23 port
    alert 127.0.0.1 has connected with us on port 23
    Telnet Port 23 closed
    Telnet port opened on 23 port
    alert 127.0.0.1 has connected with us on port 23
    Telnet Port 23 closed
    Telnet port opened on 23 port

Now when I have tried to connect with netcat on port 23 then its crashed and below is the output:

    Telnet port opened on 23 port
    alert 127.0.0.1 has connected with us on port 23
    Telnet Port 23 closed
    Telnet port opened on 23 port
    Unhandled exception in thread started by <function OpenPort23 at 0x7f8b6c9dc6a8>
    Traceback (most recent call last):
      File "port23.py", line 12, in OpenPort23
        sk.bind(('127.0.0.1',port))
    OSError: [Errno 98] Address already in use

So what should I do to remove this error and I want my socket to respond the same way as it is responding with nmap command.

Upvotes: 0

Views: 243

Answers (1)

furas
furas

Reputation: 143032

Normally system keeps port for some time (after closing socket) before it will be still available to use.

You can use this option before bind() to use port at once.

 sk.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

 import socket

 sk = socket.socket(AF_INET,SOCK_STREAM)

 sk.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

 sk.bind(('127.0.0.1', port))

Eventually do like in most tutorials. Create socket and bind it before loop, inside loop only listen(), accept() and use socket returned by accept(), and main socket close only at the end of program when you exit loop.

EDIT: something like this (it can get 5 clients at the same time)

import socket
import threading
import time

# --- functions ---

def client_handler(conn, addr):
    print('connection', addr[0], addr[1])
    conn.close()

# --- main ---

port = 23

sk = socket.socket()
sk.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sk.bind(('127.0.0.1', port))
print('Telnet opened on port', port)
sk.listen(5)

try:
    while True:
        conn, addr = sk.accept()
        t = threading.Thread(target=client_handler, args=(conn, addr))
        t.start()
except KeyboardInterrupt as ex:
    print('KeyboardInterrupt')
    sk.close()
    print('Telnet closed on port', port)

EIDT: More complex version which receive data from client until client resets connection (nmap) or you use Ctr+C (netcat)

import socket
import threading
import time

# --- functions ---

def client_handler(conn, addr):
    print('connection:', addr[0], addr[1])
    try:
        while True:
            data = conn.recv(100)
            if not data: 
                print('exit:', addr[0], addr[1])
                break
            print(data)
    except Exception as ex:
        print('Exception:', addr[0], addr[1], ex)
    finally:
        print('close:', addr[0], addr[1])
        conn.close()

# --- main ---

port = 23

sk = socket.socket()
sk.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sk.bind(('127.0.0.1', port))
print('Telnet opened on port', port)
sk.listen(5)

try:
    while True:
        conn, addr = sk.accept()
        t = threading.Thread(target=client_handler, args=(conn, addr))
        t.start()
except KeyboardInterrupt as ex:
    print('KeyboardInterrupt')
    sk.close()
    print('Telnet closed on port', port)

Upvotes: 1

Related Questions