Simple Python Socket Test

I have found that there is not a lot of documentation out there that shows you a simple way to instantiate a socket connection. Here is a simple code snippet, that shows you how to make a connection using the socket module. This would be useful for checking whether a host is listening on a particular port. This is not a full sockets implementation(no send, or recieve), but simply tests if a TCP socket is open.

import socket

#Simply change the host and port values
host = ''
port = 80

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 s.connect((host, port))
 print "Success connecting to "
 print host + " on port: " + str(port)
 print "Cannot connect to "
 print host + " on port: " + str(port)

FYI- You can test for a UDP port by changing “socket.SOCK_STREAM” to “socket.SOCK_DGRAM” .

Check out the documentation for the socket module here

Join the Conversation


  1. FYI- You can test for a UDP port by changing “socket.SOCK_STREAM” to “socket.SOCK_DGRAM” .

    It doesn’t. Connect method with UDP just checks incoming packages for target equality. It doesn’t perform any networking communications.

  2. UDP doent work. Please help. As i know, udp will not try to establish connection with server. It will start communication directly expecting a response.

Leave a comment

Leave a Reply

%d bloggers like this: