Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to open a socket in Python

I want to open a TCP client socket in Python. Do I have to go through all the low-level BSD create-socket-handle / connect-socket stuff or is there a simpler one-line way?

like image 723
Adam Pierce Avatar asked Sep 16 '08 02:09

Adam Pierce


People also ask

How do I open a socket in Python?

It is very simple to create a socket client using the Python's socket module function. The socket. connect(hosname, port ) opens a TCP connection to hostname on the port. Once you have a socket open, you can read from it like any IO object.

Is Python good for socket programming?

Python provides two levels of access to network services. At a low level, you can access the basic socket support in the underlying operating system, which allows you to implement clients and servers for both connection-oriented and connectionless protocols.


2 Answers

Opening sockets in python is pretty simple. You really just need something like this:

import socket sock = socket.socket() sock.connect((address, port)) 

and then you can send() and recv() like any other socket

like image 136
The.Anti.9 Avatar answered Sep 27 '22 22:09

The.Anti.9


OK, this code worked

s = socket.socket() s.connect((ip,port)) s.send("my request\r") print s.recv(256) s.close() 

It was quite difficult to work that out from the Python socket module documentation. So I'll accept The.Anti.9's answer.

like image 45
Adam Pierce Avatar answered Sep 27 '22 22:09

Adam Pierce