Python client server - python

i've been trying to learn how to work with Telnet in python and I just got stuck on something.
importent to mention- I have no clue about anything in this subject. IP, telnet, sockets.. Nothing at all..
let's say this is my server:
import socket
import sys
HOST = ''
PORT = 8886
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
try:
s.bind((HOST, PORT))
except socket.error , msg:
print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
sys.exit()
print 'Socket bind complete'
s.listen(10)
print 'Socket now listening'
conn, addr = s.accept()
print 'Connected with ' + addr[0] + ':' + str(addr[1])
print 'sending msg'
conn.sendall('My name is: ')
print 'msg sent'
data = conn.recv(1024)
print data
x="Hello %s and Thank you for your help! :)"%data
conn.sendall(x)
conn.close()
s.close()
Now this is just a basic thing for testing..
I was trying to create a client that wil connect to the server from a place far away, so I couldn't use localhost.
this is what i managed to do:
import socket
import sys
import time
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('85.65.110.8',8886))
data= sock.recv(1024)
lol=raw_input(data)
sock.sendall(lol)
data = sock.recv(1024)
print data
time.sleep(3)
sock.close()
the IP 85.65.110.8 is what i found from whatismyip.com- and it doesn't work even from my own computer.
I tried the IP 192.168.0.100 which works from the LAN but not from my friends house (who is testing it) and 'localhost' works aswell (still from me but not from my friend's house)
how can i change this so my friend could connect to the server?
thanks :)
(my Firewall is down and I port-forwarded.. I think... I hope so...)

If it works with the internal IP (192.168.x.x), but not with the external one (from whatsmyip, but remember it can change at any time without warning), then it is almost certainly a firewall or port-forwarding problem.
Unfortunately there's not enough information in your post to troubleshoot it (and firewalls go on SuperUser rather than StackOverflow in any case).

You probably have some router to connect to internet
so 85.65.110.8 is external address of this router.
On router you have to use port forwarding or virtual server
and set connection router 8886 <=> 192.168.0.100 8886
When someone will try to connect to 85.65.110.8 8886 then router will send this to 192.168.0.100 8886 and will send back all answers from 192.168.0.100 8886
If Internet Provider blocks some ports (for example 8886) then use 80.
It is web server port. (router 80 <=> 192.168.0.100 8886).
Then your friend will have to connect to 85.65.110.8 80 but your server will run on port 8886.
If Internet Provider changes your IP every day then you will need http://no-ip.com or http://dyndns.com .
Your friend can use telnet to test your port - or something more specialized like nmap or other port scanning tools

Related

TCP Server and Client

So i'm trying to write a TCP server and client so that when the client connects, a file is sent back from the server. Here's my code for the server:
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(10)
file_to_send = ('file_to_send.txt')
print '[*] Listening on %s:%d' % (bind_ip,bind_port)
def handle_client(client_socket):
request = client_socket.recv(1024)
print '[*] Received %s' % request
client_socket.send('')
client_socket.close(file_to_send)
while True:
client,addr = server.accept()
print '[*] Accepted connection from: %s:%d' % (addr[0],addr[1])
client_handler = threading.Thread(target=handle_client,args=(client,))
client_handler.start()
And here is my code for the client:
import socket
target_host = '0.0.0.0'
target_port = 9999
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((target_host,target_port))
client.send('ACK!')
response = client.recv(4096)
print response
When the server and client are run, the server returns the error 'Only one usage of each socket address (protocol/network address/port) is normally permitted' and when the client is run I get the error ' The requested address is not valid in its context'
Does anyone know why these errors are occurring or how I might be able to fix it.
I think this is a case of inaccurate example code. The server code you posted does not cause the issue you're describing (the client code does, but we'll get to that).
Server
The issue with the server code is that you're binding to the same (address, port) twice. Whether this is from wrong indentation or wrong logic it's tough to say, but that error message comes from binding the same protocol to the same address with the same port number more than once at the same time.
The rest of the code seems fine, though you can't do client_socket.close("some string") as you're doing here. socket.close does not accept any arguments.
Client
There's a simple solution here -- just change the target_host to something reasonable. You cannot connect to 0.0.0.0. This should be the addressable IP of the server in the smallest scope possible. Presumably if this is a toy program this is something like localhost.
(N.B. you bind the server to '0.0.0.0' to tell it to accept connections going to any destination IP. You could bind the server instead to '127.0.0.1' to inform the server that it will ONLY be known as localhost and never anything else.)
I've had a similar issue before and it was that I was running old versions of the program on the same port, restarting the PC or closing the processes in task manager should fix it.
I'm aware that this was asked over a year ago, so OP has probably restarted their PC since then, but hopefully this will help someone looking for a solution for a similar problem.

Python ConnectionRefusedError: [Errno 61] Connection refused

Ive seen similar questions but they I couldn't fix this error. Me and my friend are making a chat program but we keep getting the error
ConnectionRefusedError: [Errno 61] Connection refused
We are on different networks by the way.
Here is my code for the server
import socket
def socket_create():
try:
global host
global port
global s
host = ''
port = 9999
s = socket.socket()
except socket.error as msg:
print("Socket creation error" + str(msg))
#Wait for client, Connect socket and port
def socket_bind():
try:
global host
global port
global s
print("Binding socket to port: " + str(port))
s.bind((host, port))
s.listen(5)
except socket.error as msg:
print("Socket binding error" + str(msg) + "\n" + "Retrying...")
socket_bind
#Accept connections (Establishes connection with client) socket has to be listining
def socket_accept():
conn, address = s.accept()
print("Connection is established |" + " IP:" + str(address[0]) + "| port:" + str(address[1]))
chat_send(conn)
def chat_send(conn):
while True:
chat =input()
if len(str.encode(chat)) > 0:
conn.send(str.encode(chat))
client_response = str(conn.recv(1024), "utf-8")
print(client_response)
def main():
socket_create()
socket_bind()
socket_accept()
main()
And my client code
import socket
#connects to server
s = socket.socket()
host = '127.0.0.1'
port = 9999
s.connect((host, port))
#gets chat
while True:
data = s.recv(1024)
print (data[:].decode("utf-8"))
chat = input()
s.send(str.encode(chat))
This may not answer your original question, but I encountered this error and it was simply that I had not starting the server process first to listen to localhost (127.0.0.1) on the port I chose to test on. In order for the client to connect to localhost, a server must be listening on localhost.
'127.0.0.1' means local computer - so client connents with server on the same computer. Client have to use IP from server - like 192.168.0.1.
Check on server:
on Windows (in cmd.exe)
ipconfig
on Linux (in console)
ifconfig
But if you are in different networks then it may not work. ipconfig/ifconfig returns local IP (like 192.168.0.1) which is visible only in local network. Then you may need external IP and setting (redirections) on your and provider routers. External IP can be IP of your router or provider router. You can see your external IP when you visit pages like this http://httpbin.org/ip . But it can still need some work nad it be bigger problem.
You need simply to start server at first, and then run the client_code.
In VS Code i've opened 2 terminals. One for the server_code to be running While True, and the other one for the client_code
So this may not fix your question specifically but it fixed mine and it can help someone else I work with vscode and I use some extension that runs my code so when you want to run your server run it on your CMD or Terminal and run your client in vscode it helped me (maybe importat I work on mac so maybe spesific OS problem)
If you are connecting to a host:port that is open but there is no service bound to it you may see this IIRC. Eg with ssh you sometimes see this while attempting to connect to a server that is booting but sshd is not running.
This Code Not Valid For Chatting, you have to use unblocking sockets and select module or other async modules

Basic TCP Connection

I am trying to control some test equipment with a TCP connection. The equipment comes with software that you are able to control over TCP. Basically, you can input the IP address and port of the client computer and there is also an indicator light that shows when there is an open listening session on that port (this is all on the equipment software interface)
I have tested this using SocketTest3 (free software) and am able to start a listening session as well as send commands from another computer. Now, I want to control the equipment with Python. I am running the code for the server and client on the same machine as the test equipment (using local IP address). When I simply run the code (with the equipment software closed) I am able to send, receive, and print the messages I send. When I have the equipment software open (necessary for control) I am able to start a listening session (indicator light shows up on equipment software), but nothing happens (no errors and nothing received) when I send commands. The messages are also not sent back to the client to print.
Any ideas? It's probably something very simple that I'm missing.
Server code:
import sys
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
TCP_IP = '127.0.0.1'
TCP_PORT = 8001
s.bind((TCP_IP, TCP_PORT))
s.listen(5)
connection, client_address = s.accept()
BUFFER_SIZE = 20
print 'Address: ', client_address
while 1:
print "receiving..."
data = connection.recv(BUFFER_SIZE)
print data
if not data: break
print "received data:", data
connection.send(data) # echo
connection.close()
Client code:
import socket
TCP_IP = '127.0.0.1'
TCP_PORT = 8001
BUFFER_SIZE = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
print "sending message..."
s.sendall('ST<CR>') # Send command
print "receiving message..."
data = s.recv(BUFFER_SIZE)
s.close()
print "received data:", data
For those wondering what is missing from camerausb's code, I think he was not seeing anything from the client's print statement because he did not use repr() to format the data. I had a similar problem, but this worked for me:
print 'Received', repr(data)

Unable To Connect Python Sockets On Different Computers

I recently wrote a code for a small chat program in Python. Sockets connect fine when I connect them from different terminals on the same system. But the same doesn't seem to happen when I connect them from different computers which are connected over the same Wifi network.
Here's the server code:
#!/usr/bin/env python
print "-"*60
print "WELCOME TO DYNASOCKET"
print "-"*60
import socket, os, sys, select
host = "192.168.1.101"
port = 8888
connlist = []
try:
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
print "Socket Successfully Created."
connlist.append(s)
s.bind((host,port))
print "Socket Successfully Binded."
s.listen(10)
print "Socket is Now Listening."
except Exception, e:
print "Error : " + str(e)
sys.exit()
def air(sock,message):
for socket in connlist:
if socket != sock and socket != s:
try:
socket.sendall(message)
except:
connlist.remove(socket)
while 1:
read_sockets,write_sockets,error_sockets = select.select(connlist,[],[])
for sock in read_sockets:
if sock == s:
conn, addr = s.accept()
connlist.append(conn)
print "Connected With " + addr[0] + " : " + str(addr[1])
else:
try:
key = conn.recv(1024)
print "<" + str(addr[1]) + ">" + key
data = raw_input("Server : ")
conn.sendall(data + "\n")
air(sock, "<" + str(sock.getpeername()) + ">" + key)
except:
connlist.remove(sock)
print "Connection Lost With : " + str(addr[1])
conn.close()
s.close()
Here's the client script:
#!/usr/bin/env python
print "-"*60
print "WELCOME TO DYNASOCKET"
print "-"*60
import socket, os, sys
host = "192.168.1.101"
port = 8888
try:
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
print "Socket Successfully Created."
s.connect((host,port))
print "Connected With " + host + " : " + str(port)
except socket.error, e:
print "Error : " + str(e)
while 1:
reply = raw_input("Client : ")
s.send(reply)
message = s.recv(1024)
print "Server : " + message
s.close()
When I try to connect The client From a different computer I get this error :
Error : [Errno 10060] A Connection attempt failed because the connected party
did not respond after a period of time, or established connection failed
because connected host has failed to respnd.
Your are binding your server only to the local host, so that connections from other hosts are blocked.
Try:
s.bind(("0.0.0.0",port))
I experienced this problem and it took me a many hours to figure this out and I found that (like many others said #Cld) it is your firewall blocking the connection. How I fixed this:
Try to run the server onto the machine that you trying to connect from.
(For example, if you want to run the server on machine A and connect from machine B, run the server on machine B).
If you are on windows (I am not sure about Mac or Linux) it will popup with with the firewall pop-up, which will allow you to give permission to your program to access your private network.
Simply tick the box that says:
"Private networks, such as my home or work network"
and Press allow access
That's it! You've fixed that particular issue. Now feel free to test the server on that machine or close the server and go back to your main machine, which will host that server and run it. You should see that it is now working.
I hope this has helped you, as it is my first post!
EDIT: I also did what #Daniel did in his post with changing the s.bind to include '0.0.0.0'.
I had this same problem for quite sometime, and creating tcp tunnels with ngrok worked for me. You can check it out here
For simple sockets application on your pc, just expose the port you're using by ngrok tcp <port_number>, bind the server socket to localhost and port exposed, and use the url of the tunnel with the port number at client side (typically looks like 0.tcp.us.ngrok.io and a port number).
You can even make multiple tunnels on the free account (needed in my case) by specifying the --region flag: https://ngrok.com/docs#global-locations

How to connect two computers on the same network using python

This is the server side program
import socket
s = socket.socket()
host = socket.gethostname()
port = 9077
s.bind((host,port))
s.listen(5)
while True:
c, addr = s.accept()
print("Connection accepted from " + repr(addr[1]))
c.send("Thank you for connecting")
c.close()
This is the client program
import socket
s = socket.socket()
host = socket.gethostname()
port = 9077
s.connect((host, port))
print s.recv(1024)
When i run these two programs on the same computer, it works perfectly.
But when i run the client and server programs in two different computers on the same network, the program doesn't work.
Can anyone please tell me how to send message from one computer to another on the same network.
This is the first time i'm doing any network programming. Any help would be appreciated
Thanks in advance
You are connecting from the client to the client's computer, or well attempting to, because you are using the client's hostname rather than the servers hostname/ip address.
So, to fix this change the line s.connect((host, port)) so that the host points to the servers ip address instead of the client's hostname.
You can find this by looking at your network settings on the server and doing the following:
host = "the ip found from the server's network settings"
host must be edited to the server's ip if the server is not the same computer.

Categories

Resources