How to send messages over internet socket - python

My server (listening) is as:
import os
from socket import *
host = ""
port = 1337
buf = 1024
addr = (host, port)
UDPSock = socket(AF_INET, SOCK_DGRAM)
UDPSock.bind(addr)
print("Waiting to receive messages...")
while True:
(data, addr) = UDPSock.recvfrom(buf)
data=data.decode('ascii')
print("Received message: " + data)
if data == "exit":
break
UDPSock.close()
os._exit(0)
and my client is
import os
from socket import *
host = "MY INTERNET IP"
port = 1337
addr = (host, port)
UDPSock = socket(AF_INET, SOCK_DGRAM)
while True:
data = input("Enter message to send or type 'exit': ")
data=data.encode('ascii')
UDPSock.sendto(data, addr)
if data == "exit":
break
UDPSock.close()
os._exit(0)
so I need to know, how do I transmit these messages over internet? i have all my ports open on my network yet i can not receive any messages while trying to do that. My server is listening on port 1337 and my client is transmitting to MY INTERNET IP where a server is listening on the port it is transmitting on. so how do I get this to work, what do i do wrong? thing is, it works while doing lan. it's cozy, but very pointless since i would like to transmit text over web
EDIT
Got my friend to run client side. Python just returned 4.
Nothing happened on my side.

Related

Python console chat with socket

I'm writing a simple console chat with server and client. When receiving a message from the first client server should send it to the second client and vice versa. But when first client sends a message to the server it returns back and doesn't reach the second client. Maybe there is a problem in receiving() function.
Here is my client.py:
import socket
from _thread import *
def recieving(clientSocket):
while True:
encodedMsg = clientSocket.recv(1024)
decodedMsg = encodedMsg.decode('utf-8')
print(decodedMsg)
def chat(clientSocket, name):
msg = input()
encoded_msg = f'[{name}] {msg}'.encode('utf-8')
clientSocket.send(encoded_msg)
def main():
serverAddress = (socket.gethostname(), 4444)
clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientSocket.connect(serverAddress)
name = input('Enter your name: ')
start_new_thread(recieving, (clientSocket,))
while True:
chat(clientSocket, name)
if __name__ == "__main__":
main()
And server.py:
import time
import socket
from _thread import *
def listen(clientSocket, addr):
while True:
encodedMsg = clientSocket.recv(1024)
decodedMsg = encodedMsg.decode('utf-8')
currTime = time.strftime("%Y-%m-%d-%H.%M.%S", time.localtime())
for client in clients:
if addr != client:
clientSocket.sendto(encodedMsg, client)
print(f'[{currTime}] {decodedMsg}')
def main():
serverAddress = (socket.gethostname(), 4444)
global clients
clients = []
serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serverSocket.bind(serverAddress)
serverSocket.listen(2)
while True:
clientSocket, addr = serverSocket.accept()
if addr not in clients:
clients.append(addr)
print(f'{addr} joined chat')
start_new_thread(listen, (clientSocket, addr))
if __name__ == '__main__':
main()
sendto doesn't work as expected if its socket is connected. It just sends to the connected socket, not the specified address.
Therefore, listen needs to be able to access the open socket of each client in order to write to it.
Currently clients is a list of addresses, but you could change it to a dict of address to socket mappings:
def main():
global clients
clients = {}
Then when you get a new client connection, save address and socket:
clientSocket, addr = serverSocket.accept()
if addr not in clients:
clients[addr] = clientSocket
print(f'{addr} joined chat')
start_new_thread(listen, (clientSocket, addr))
Finally, in listen, write to each other client's socket, not the connected clientSocket for that listen thread:
for client in clients:
if addr != client:
print(f"sending message from {addr} to {client}")
clients[client].send(encodedMsg)
There's a number of other problems with your code.
Sockets are not thread safe. So there is a race condition if 2 clients happen to write the same thing at the same time; the writes could be interpolated and the messages munged up.
If a client disconnects, the server doesn't handle the disconnection well. If the server disconnects, the clients go into an infinite loop as well.

UDP Hole punching in python

I am trying to establish a peer to peer communication using UDP hole punching. I am first establishing a connection with the server and then trying to make communication between 2 clients, but I am not able to communicate between 2 computers that are behind 2 different NATs as I am not understanding what IP address and port must I enter for the establishment of communication.
Please tell me what changes must I make in the code below so that 2 computers are able to communicate.
P.S : External IP doesn't seem to work and I am not supposed to use any additional tool like ngrok
Server.py
import socket
import struct
import sys
server_listening_port = 12345
sockfd = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sockfd.bind(("", server_listening_port))
print("Listening on the port " + str(server_listening_port))
client_requests = []
while True:
data, addr = sockfd.recvfrom(32)
client_requests.append(addr)
print("Connection from: " + str(addr))
if len(client_requests) == 2:
break
client_a_ip = client_requests[0][0]
client_a_port = client_requests[0][1]
client_b_ip = client_requests[1][0]
client_b_port = client_requests[1][1]
message = ": "
sockfd.sendto(str(client_a_ip).encode("utf-8") + message.encode("utf-8") + str(client_a_port).encode("utf-8"), client_requests[1])
sockfd.sendto(str(client_b_ip).encode("utf-8") + message.encode("utf-8") + str(client_b_port).encode("utf-8"), client_requests[0])
sockfd.close()
Above is the rendezvous server
ClientA.py
import socket
import struct
import sys
import time
master = ("Server_IP", Port)
#Create dgram udp socket
try:
sockfd = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
message = "Hello"
sockfd.bind(('', 0))
sockfd.sendto(message.encode("utf-8"), master)
except socket.error:
print("Failed to create socket")
sys.exit()
# #Receiving peer info from server
peer_data, addr = sockfd.recvfrom(1024)
print (peer_data)
print("trying to communicate with peer")
peer_ip = peer_data.decode("utf-8").split(":")[0]
peer_port = int(peer_data.decode("utf-8").split(":")[1])
peer = (peer_ip, peer_port)
while 1:
message1 = input(str("You:>>"))
message = message.encode("utf-8")
sockfd.sendto(str(message).encode("utf-8"), peer)
incoming_msg, sendaddr = sockfd.recvfrom(1024)
incoming_msg = incoming_msg.decode("utf-8")
print("ClientB:>>",incoming_msg)
Above code is Client A
ClientB.py
import socket #For sockets
import struct
import sys #For exit
import time
master = ("Server_IP", port)
me = ("ClientB_IP", port)
#Create dgram udp socket
try:
sockfd = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
message = "Hello"
sockfd.bind(('', 0))
sockfd.sendto(message.encode("utf-8"), master)
except socket.error:
print("Failed to create socket")
sys.exit()
# #Receiving peer info from server
peer_data, addr = sockfd.recvfrom(1024)
print (peer_data)
print("trying to communicate with peer")
peer_ip = peer_data.decode("utf-8").split(":")[0]
peer_port = int(peer_data.decode("utf-8").split(":")[1])
peer = (peer_ip, peer_port)
while 1:
incoming_msg, sendaddr = sockfd.recvfrom(1024)
incoming_msg = incoming_msg.decode("utf-8")
print("ClientA:>>", incoming_msg)
message = input(str("You :>>"))
message = message.encode("utf-8")
sockfd.sendto(str(message).encode("utf-8"), peer)
Above is client B
I am facing problem only in the IP address and port. So , please do help me with it to establish communication between 2 computers behind 2 different NATs
I'm currently on the same problem and I want to program it for myself. With some research I found a really good paper explaining the process in detail.
I let you know if I succeed.
https://bford.info/pub/net/p2pnat/

Connection between client and server fails, send/recv doesnt work (python)

I have put together a server and client code to use in a messaging app. When I run the server and starts one client, everything works fine. When I start a second client, I can send messages from the first client and the second client will recieve them. I can send one message from the second client and the first client will recieve this first message. But after this message, the second client can not send or the server can not receive the data for some reason. The first client can still send messages.
I dont know where the mistake is, but I believe either the client can not .send() or the server can not .recv().
(I am quite new to programming so the code might be quite messy and not the most understandeble, and maybe there are several flaws...)
The server code
import socket
from _thread import *
import sys
HOST = "127.0.0.1"
PORT = 12000
client_socket = set()
def threaded(conn):
while True:
try:
data = conn.recv(1024).decode()
if not data:
print("Lost connection")
break
for conn in client_socket :
conn.send(data.encode())
except:
break
print("Gone")
conn.close()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(5)
print("Server is up and running")
while True:
conn, addr = s.accept()
print("Connected to", addr)
client_socket .add(conn)
start_new_thread(threaded, (conn, ))
The client code
import threading
import socket, sys
HOST = "127.0.0.1"
PORT = 12000
check= ""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
def background():
while True:
answer= s.recv(1024).decode()
if check!= answer and answer!= "":
print(answer)
threading1 = threading.Thread(target=background)
threading1.daemon = True
threading1.start()
while True:
message= input()
if message!= "":
s.send(message.encode())
check = message

I'm having a problem with my Python socket program [WinError 10057]

I was programming a simple client-server socket program that worked on two different computers.
The server is a desktop with a static ip address, and the client is a laptop connected to a Wi-Fi. Both are using Windows 10 as operating system.
I also opened the firewall port.
Here is my code.
This code works well within one computer, but WinError 10057 occurs when another computer(my laptop) tries to connect to the server.
server.py
from socket import *
import sys
HOST = '0.0.0.0'
PORT = 16161
BUFSIZE = 1024
ADDR = (HOST, PORT)
CLIENT_NUM = 5
serverSocket = socket(AF_INET, SOCK_STREAM)
serverSocket.bind(ADDR)
print('bind')
serverSocket.listen(CLIENT_NUM)
print('listen')
while True:
try:
connectionSocket, addr_info = serverSocket.accept()
print('accept')
print('--client information--')
print(connectionSocket)
data = connectionSocket.recv(BUFSIZE)
print('Received data:', data.decode())
connectionSocket.send('OK'.encode())
connectionSocket.close()
except KeyboardInterrupt:
sys.exit(0)
client.py
from socket import *
import sys
HOST = '*.*.*.*' # server's ip address
PORT = 16161
BUFSIZE = 1024
ADDR = (HOST, PORT)
clientSocket = socket(AF_INET, SOCK_STREAM)
try:
clientSocket.connect_ex(ADDR)
clientSocket.send('Hello!'.encode()) # WinError 10057 occurs
except Exception as e:
print(e)
print('%s:%s' % ADDR)
sys.exit(1)
print('connect is success')
receive = clientSocket.recv(BUFSIZE)
print(receive.decode())
clientSocket.close()
I've fixed it. I asked my organization to open the firewall ports, and the connection was successful when the firewall ports were opened.

How to connect to server, listen for arbitrary time and send back data

I'm trying to:
Connect to a server/port
Listen for x seconds
Receive user input
Send user input to server
Go back to step 2
So far, I've written the following code, but it's not working properly receiving input after the first send. Any help would be greatly appreciated.
import socket
import select
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(('domain.com', 1234))
client_socket.setblocking(0)
timeout = 5
while True:
while True:
ready = select.select([client_socket], [], [], timeout)
if ready[0]:
data = client_socket.recv(4096)
print data
else:
break
data = raw_input("Enter input:")
client_socket.send(data)
You need to have separate server side code and client side code. This article has been referred.
Server binds to a port and listens for clients
server.py
import select
import socket
# Create a TCP/IP socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setblocking(0)
# Bind the socket to the port
server_address = ('localhost', 1234)
server.bind(server_address)
# Listen for incoming connections
server.listen(5)
# Sockets from which we expect to read
inputs = [ server ]
# Sockets to which we expect to write
outputs = [ ]
while inputs:
readable, writable, exceptional = select.select(inputs, outputs, inputs)
# Handle inputs
for s in readable:
if s is server:
# A "readable" server socket is ready to accept a connection
connection, client_address = s.accept()
connection.setblocking(0)
inputs.append(connection)
else:
data = s.recv(1024)
if data:
print "Receiving data from client"
print data
else:
inputs.remove(s)
s.close()
Client first establishes a connection with the server and then keeps on sending user input to the server.
client.py
import socket
server_address = ('domain.com', 1234)
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(server_address)
while True:
data = raw_input("Enter input:")
sock.send(data)
Open terminal.
Run server in background:
python server.py &
Run client after that:
python client.py

Categories