Connection using "socket" library - python

I am working on a python program which will allow me to send and receive data between PCs. I have managed to get it to work in my local network and wanted to set it up to be able to connect from the internet. I opened the port 1234 in my router and used the local IP on the server.py and puclic IP on the client, but the server.py seems to not receive any data. What am I doing wrong here?
The example code is something like this (it works for local networks, but on separate PCs only, IP address, of course, is just an example and probably will not work for anyone else):
server.py:
import socket
import time
import pickle
IP = "192.168.1.69"
PORT = 1234
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((IP, PORT))
server_socket.listen()
print(f'Listening for connections on {IP}:{PORT}...')
client_socket, client_adress = server_socket.accept()
print(pickle.loads(client_socket.recv(1024)))
client_socket.send(pickle.dumps('DONE'))
time.sleep(1)
client_socket.send(pickle.dumps('boi'))
print(client_socket, client_adress)
client.py:
import socket
import pickle
import time
IP = "192.168.1.69"
PORT = 1234
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((IP, PORT))
client_socket.setblocking(False)
client_socket.send(pickle.dumps("NICE."))
time.sleep(1)
print(pickle.loads(client_socket.recv(1024)))
time.sleep(1)
print(pickle.loads(client_socket.recv(1024)))
Thank you.

Related

Socket doesn't work when using public ip on same machine

I made a program using Python that should connect to the server using a socket. I run the script on the same machine and when I tried with private ip it worked but public doesn't.
Client:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("46.126.xx.xxx",9454)) #I put the public ip of the server (same machine)
msg = s.recv(1024)
print(msg.decode("utf-8"))
Server
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("0.0.0.0",9454))
s.listen(5)
while True:
clientsocket, address = s.accept()
print(f"Connection from {address} has been established!")
clientsocket.send(bytes("Welocme to the server", "utf-8"))
It does not give me any errors. I made lots of reasearch but couldn't figure out what the problem is.
Well I just put the public ip of the server in the client socket.connect() and expected it to connect but it didn't. I am running this on the same machine.

Python socket ipv6 over network not working

I am trying to connect a server to a client in python with sockets.
The problem is that with ipv6 binding, it works on my local network. What I want is to connect it to another network. These programs are written in Python 3
Here is the code of server.py:
import socket
HOST = someip
PORT = someport
server = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
server.bind((HOST, PORT))
server.listen()
Source code of client.py:
import socket
HOST = someip
PORT = someport
client = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
client.connect((HOST, PORT))
I think it is a port forwarding problem.
I know the code does nothing right now, but I want to first establish the connection.
When the server receives a request, we need to put it in a loop to accept it.
Like this
import socket
HOST = someip
PORT = someport
server = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
server.bind((HOST, PORT))
server.listen()
while True:
try:
conn, addr = server.accept()
print(f"New request from {addr}")
except KeyboardInterrupt:
server.close()

Socket Error : No connection could be made because targeted machine actively refused it

Note : This problem has been completely solved, as was am running client.py before server.py
Just got started with socket programming, I have created the below code and expecting to print some byte message, but it isn't doing that.
I just want to make the message available for any person on any
machine. But it's refusing by the machine to do that.
Here is my code:
server.py
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
port = 12048
s.bind((socket.gethostname(), port))
s.listen()
while True:
c, addr = s.accept()
print("Got connection from", addr)
c.send(bytes("Thank you", "utf-8"))
client.py
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
port = 12048
s.connect(('192.168.0.1', port))
msg = s.recv(1024)
print(msg.decode("utf-8"))
Some images to better explain my errors:
Any help would be appreciated!!!
It looks like in the server.py script you use s.bind((socket.gethostname(), port)) where socket.gethostname() is a hostname, but in the client.py script you use s.connect(('192.168.0.1', port)) where '192.168.0.1' is the hostname you are trying to connect.
I think there you have socket.gethostname() != '192.168.0.1' and that's the problem.
Also, you can bind to all available IP addresses on the host using this solution Python socket bind to any IP?
Let's use listen_ip = socket.gethostbyname(socket.gethostname()) for connection since socket.gethostname() may return hostname instead of IP and it will not be solved by python dns resolver in local network if it was local name, not DNS.
and use it later as s.bind((listen_ip, port)) and s.connect((listen_ip, port))
After some debugging I've got a working solution for you
There are the scripts required.
server.py
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostbyname(socket.gethostname())
port = 12_048
s.bind((host, port))
s.listen()
print("Server listening # {}:{}".format(host, port))
while True:
c, addr = s.accept()
print("Got connection from", addr)
c.send(bytes("Thank you", "utf-8"))
client.py
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = '192.168.1.162' # The IP printed by the server must be set here
# or we can set it using env variable named SERVER_IP
if 'SERVER_IP' in os.environ:
host = os.environ['SERVER_IP']
port = 12048
print("Connecting to {}:{}".format(host, port))
s.connect((host, port))
msg = s.recv(1024)
print(msg.decode("utf-8"))
In a chat conversation we concluded that the hardcoded IP in the question is not the correct one. This solution does have the IP he needed but it will be different in each case. Remeber that server.py needs to be launched first, and when you see the printed Server listening # IP:12048, write that IP in client.py and launch it. Client does need to be launched after seeing that line even if you already know the IP, as the server needs some time to be ready and the client will crash if it tries to connect to the server while it is not ready.
server.py
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostbyname(socket.gethostname())
port = 12048
s.bind((host, port))
s.listen()
print("Server listening # {}:{}".format(host, port))
while True:
c, addr = s.accept()
print("Got connection from", addr)
c.send(bytes("Thank you", "utf-8"))
client.py
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = '192.168.1.162' # The IP printed by the server must be set here
port = 12048
print("Connecting to {}:{}".format(host, port))
s.connect((host, port))
msg = s.recv(1024)
print(msg.decode("utf-8"))

Keep Client connection alive

I am a beginner in python socket programming. My question is, I have a TCP server in listen mode at that time client will send data to the server. But when my TCP server is unavailable at that I want a client to go and check for connection every time (something like try exception method with while loop).
I have tried tricks but that didn't work out, it gives o/p like connection refused when my TCP server is unavailable. Below is my code help me with same.
# client.py
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()
port = 2195
s.connect((host, 2195))
while 1:
try:
print "Try loop"
s.sendall("Welcome to Python\r\n")
print "Try loop2"
time.sleep(5)
except:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
s.close()
I have tried many solutions but below code works for me.
client.py
import socket
import time
while True:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1)
host = socket.gethostname()
port = 2195
try:
s.connect((host , port))
s.sendall("Welcome to Python\r\n")
except:
print "Error"
time.sleep(5)
s.close()

What do I do to make this socket to a websocket?

I've got this code at the moment, it's a simple socket server:
import socket
import time
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()
port = 9999
serversocket.bind((host, port))
serversocket.listen(5)
while True:
clientsocket,addr = serversocket.accept()
print(str(addr) + "connected")
test = "Package"
clientsocket.send(test.encode('utf-8'))
clientsocket.close()
I also made a client that gets the message. However, how do I make it so that when I type in the address of my socket on for example Chrome, it displays "Package". I have basic knowledge on handlers and such, but I can't find any DIY websocket tutorials on the internet.
I do not want to use for example tornado, I want to make a simple one myself
Thank you very much in advance!

Categories

Resources