I have an example of a server that gets commands and returns answers in python:
import socket
import time
import random
CommandDict = {"TIME" : time.strftime("%d-%m-%Y"),"NAME": "Ori","RANDOM": str(random.randint(0,10))}
server_socket = socket.socket()
server_socket.bind(('127.0.0.1',8820))
server_socket.listen(5)
while True:
print "Waiting for commands"
(client_socket, client_address) = server_socket.accept()
client_data = client_socket.recv(1024)
print "GOT COMMAND FROM " + client_address[0] + " : " + client_data
try:
client_socket.send(CommandDict[client_data])
except Exception:
client_socket.send("ERROR!")
client_socket.close()
server_socket.close()
i tried a syn flood attack on it and it crashed. i want to defend it from syn flood attacks, how could i do it? i'm new to socket programming so i would be happy to get some advices ^_^
First of all you need a better server. As @Nikolai N Fetlissov pointed out, you are leaking file descriptors since you never closing the client connections.
Look at this example to see how to avoid this leak:
http://ilab.cs.byu.edu/python/socket/echoserver.html
In particular, note where the
client.close()
call is made and at what indentation level it is.Next, you code only processes one command from the client. Have a look here:
http://code.activestate.com/recipes/578247-basic-threaded-python-tcp-server/
for a discussion on writing a threaded server which can handle multiple connections and multiple commands from each connection.
Finally, a user-space, socket-based program (more so, written in an interpreted language) is too slow to handle a real SYN flood in just any way. The standard approach is to use firewall software (and, after a certain margin, hardware) for that.