Following is the Server and Client code written for Python 3
Server code:
import sys
from socket import socket, gethostbyname, AF_INET, SOCK_STREAM
PORT_NUMBER = 5060
SIZE = 1024
hostName = gethostbyname( '0.0.0.0' )
recvSocket = socket( AF_INET, SOCK_STREAM )
recvSocket.bind((hostName, PORT_NUMBER))
recvSocket.listen(5)
print("Listening for client...")
(conn,addr)=recvSocket.accept()
print ("Test server listening on port {0}\n".format(PORT_NUMBER))
print("Connected to client at address {0}\n".format(addr))
print("Connection is ",conn)
Client Code:
import sys
from socket import socket,AF_INET,SOCK_STREAM,gethostbyname
hostname=gethostbyname('0.0.0.0')
print ("Creating")
sendsocket=socket(AF_INET,SOCK_STREAM)
print ("Connecting socket")
sendsocket.connect(('192.168.4.39',5060))
print ("connected")
data=input("Enter value")
sendsocket.sendto(data.encode('utf-8'),(SEND_IP,SEND_PORT))
Now the situation that I am facing is as follows:
1st Scenario
Server code is running on a Windows System and the client code is
running on a Linux system
Result: Client code is getting stuck after printing "Connecting socket"
2nd Scenario
Server Code is running on a Linux System and the Client code is running on
Windows system
Result: Getting output as Expected.
Why is this behaviour occurring? Does connect() function has any kind of problem or the code is having some problem?
NOTE: Both Server and Client system is on the same Network. 192.168.4.39 is the IP Address where the server code is running.
First make sure client and server connected well.try ping each other.
Then do it manually like this:
Ssocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
should work
Related
I'm trying to have a simple UDP echo client/server communicate with each other. The client program (which runs in the host Windows) sends packets to the server (which runs in WSL-2), and the server receives them, but the server's reply is never reaches the client.
import sys
from socket import *
from select import select
client = sys.argv[1].startswith("c")
host = sys.argv[2] if len(sys.argv) > 2 else "127.0.0.1"
port = 8080
sd = socket(AF_INET, SOCK_DGRAM)
def poll():
readable, writable, errorset = select([sd], [sd], [sd], 0)
return sd in readable
if client:
sd.connect((host, port))
sd.setblocking(0)
sd.send(b"Hello!")
while not poll():
pass
data, addr = sd.recvfrom(65535)
print(f"RECV {addr} => {data}")
else:
sd.bind((host, port))
print(f"Listening on {host}:{port}")
sd.setblocking(0)
sd.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
while True:
while poll():
data, addr = sd.recvfrom(65535)
print(f"RECV {addr} => {data}")
sd.sendto(data.decode("utf-8").upper().encode("utf-8"), addr)
The output on Windows:
udpecho.py client 172.25.154.133
The output on Linux:
$ python3 udpecho.py server 172.25.154.133
Listening on 172.25.154.133:8080
RECV ('172.25.144.1', 57661) => b'Hello!'
And now I'm stumped. TCP connections work ok so it must only be a UDP thing, but I don't know what to try next.
Running Windows 10 Home edition and hosting Ubuntu-20.04 in WSL 2.
This sounds like this Github issue, where UDP packets smaller than 12 bytes don't make it from WSL2 to the host Windows interface.
If so, then a reported workaround is to turn off transmission checksumming in WSL2 via:
ethtool -K eth0 tx off
It sounds like this may be a Hyper-V networking issue that can be reproduced outside of WSL2, and the Microsoft team says it is under investigation.
I have an Ipad and a raspberry pi. I want to broadcast a simple message from my ipad to my raspberry pi using python's library: "socket". I have a file called server.py in my raspberry pi. I have another file called client.py in my Ipad. server.py should await a connection from the Ipad, and accept it. client.py should send the broadcast message.
server.py
import socket
import threading
bind_ip = '0.0.0.0'
bind_port = 9999
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((bind_ip, bind_port))
server.listen(5)
print("[*] Listening on {}:{}".format(bind_ip, bind_port))
def handle_client(client_socket):
request = client_socket.recv(1024)
print('received: {}'.format(request))
client_socket.send(b'ACK!')
client_socket.close()
while True:
client, addr = server.accept()
print("[*] Accepted connection from: {}:{}".format(addr[0], addr[1]))
client_handler = threading.Thread(target=handle_client, args=(client,))
client_handler.start()
client.py
import socket
HOST = "0.0.0.0"
PORT = 9999
sock = socket.socket()
print("Attempting connection... ")
sock.connect((HOST, PORT))
print("Connected")
I first ran server.py on my raspberry pi, then ran client.py on my Ipad. However, the following error message greeted me when I ran client.py:
[Errno 61] Connection refused
I made sure the server was running properly, and I checked where the client was connecting to. It should have worked.
Please help me.
I would like to point out that there are so many mistakes in that code. I presume that you are totally new with sockets.
(Also try putting 'your-server's-local-ip' in the bind_ip and HOST in server.py and client.py respectively if both of your server and client are connected to the same network)
Even though you connect with the server you'd still get greeted with another errors.
Let me start with server.py:
In server.py you are using handle_client function to recieving a message from the client while at the client end you are not sending anything.
After that you're recieving the message from the client while the client is not sending anything.
There is no broadcast function for sending the message to every connected client
The main issue is that you've not learned the basics of the sockets, my only suggestion to you would be to, start things small and then increase the complexity but here, that case is totally opposite.
You can also refer to this video to learn the basics : https://youtu.be/u4kr7EFxAKk
I made a socket to see how it works.
Basically my intention for testing was to run commands in client computer cmd
First I made the server to receive a connection from my other script client
import socket
HOST = '192.168.100.xx' #my computer ipv4
PORT = 50000
server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server.bind((HOST,PORT))
server.listen(5)
print('Server waiting connection...')
conn,addr = server.accept()
print('Connection established!')
print('Connected in addr: {}\n'.format(addr))
while True:
cmd = str(input('command>'))
conn.send(str.encode(cmd))
response = str(conn.recv(1024),"utf-8")
print(response)
if cmd == 'quit':
break
server.close()
Then I made the client:
import socket
import subprocess
import os
HOST = '192.168.100.xx' #ipv4 from my computer (server)
PORT = 50000
client = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
client.connect((HOST,PORT))
print('Connecting to the server {}'.format(HOST))
while True:
command = client.recv(1024).decode()
print('Server command>'+command)
cmd = subprocess.Popen(args=command,shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
output = (cmd.stdout.read() + cmd.stderr.read()).decode("utf-8", errors="ignore")
client.send(str.encode(str(output)+ str(os.getcwd()) +'$'))
Here's how I get my IPv4 address:
Initially when I tested it on a machine on my network this worked fine, but when I sent the client to a friend far away to run it, it didn't work.
I would like to know what I do to be able to use my socket server to connect with socket client in any corner of the world.
You are using a local ip which allows people connected only to your router connect.
So you need to use your public ip address. (Click Here to check your IP)
Open a port in your router. for example: 1234.
Dont know how? See this video.
Want to learn about it? See this video.
Once you do that, change the port in your code to the port you opened on the router page.
and then change the ip in the client code to your public ip.
Now your friend should be able to connect to your server.
(also you need to have static ip and not dynamic ip)
I was learning about networking and I have some trouble understanding what went wrong.
I created a Client and a Server script:
Server:
import socket
s = socket.socket()
host = socket.gethostname()
port = 12345
s.bind((host,port))
s.listen(5)
while True:
c, addr = s.accept()
print ("Got connection from: " ,addr)
c.send("Thanks".encode('utf-8'))
# c.sendto(("Thank you for connection").encode('utf-8'), addr)
c.close()
and Client:
import socket
s=socket.socket()
host=socket.gethostname()
port = 12345
s.connect((host,port))
c=s.recv(1024)
print (c)
s.close
When I am trying to run from my computer I have no problem (both scripts)
But when I am running the Client from another Computer, the following error pops up for the Client: ConnectionRefuseError: WinError10061 No connection could be made because the target machine actively refused it.
Got any idea what could fix this?
The problem was that I wasn't referring to the server IP when running from another computer, I fixed it by passing the server IP, in the client script, like this host = "10.x.x.x"
Sorry for creating a useless question!
I've tried to connect two computers with a socket in Python and I don't know why it doesn't work. The files are from internet and it compiles for me but without any results.
The server.py:
#!/usr/bin/python
import socket
s = socket.socket()
host = ''
port = 12345
s.bind((host, port))
s.listen(5)
while True:
c, addr = s.accept()
print 'Got connection from', addr
c.send('Thank you for connecting')
c.close()
and the client.py:
#!/usr/bin/python
import socket
s = socket.socket()
host = # here I put the ip of the server's laptop
port = 12345
s.connect((host, port))
print s.recv(1024)
s.close()
What's wrong?
You have to run the server first. Then run the client at the same time with the IP of the server (I used localhost because it was running on one computer, maybe you should try if that works). The code worked fine for me, every time I ran the client, the server printed a message. If it doesn't work for you, maybe your firewall is not letting you open ports.
Just for the future, please always post any error messages you see.
BTW, isn't this the Python Documentation example for sockets?