How to connect python socket client side to server socket with url?
Asked 4 years ago Active 4 years ago Viewed 5k times
I am trying to create a client to connect to a server with given url address.
1 I used this way
host_ip = socket.gethostbyname('HOST_NAME')
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('127.0.0.1', 0))
sock.connect((host_ip, 8080))
but it printed the following error
OSError: [Errno 22] Invalid argument
Can someone explain me why is wrong and give me a solution?
python sockets
Share Improve this question Follow asked Mar 25 '17 at 16:35
Jose Pinho
33 1 6
Why are you bind ing the socket? This is used if you are the server. – ForceBru Mar 25 '17 at 16:37
1 Answer Active Oldest Votes
You don't have to bind your socket, this is done server-side.
2 Here's the example code from the documentation for socket :
import socket
HOST = 'your-url.net' # The remote host
PORT = 8080 # The same port as used by the server
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
s.sendall(b'Hello, world')
data = s.recv(1024)
print('Received', repr(data))
This is a simple snippet, which connects to the server, sends some data, and prints the
response.
Share Improve this answer Follow answered Mar 25 '17 at 18:34
Ealhad
1,224 15 24