I have begun learning Socket Programming and Issue I faced is. I am unable to connect Sockets when On two different network ( To be specific : I am using Web-host and Cgi programming to create python socket Server and my goal is to connect to that socket using desktop client python application )
My Server Coad : Location Public_html/cgi-bin/serverSocket.py
#!/usr/bin/python
print "Content-type: text/html\n\n";
import cgitb
import socket
cgitb.enable()
def main():
host = 'localhost'
port = 8111
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.bind((host,port))
except socket.error as e:
print(str(e))
s.listen(10)
c,addr = s.accept()
print("Connection From : " + str(addr))
while True:
data = c.recv(1024)
if not data:
break
print ("From Connected user : " + str(data.decode()))
data =str(data.decode()).upper()
print ("sending :" + str(data))
c.send(data.encode())
if __name__ == '__main__':
main()
And Client Program : Location On My Local Computer C:/Desktop
#!/usr/bin/python
print "Content-type: text/html\n\n";
#Client Socket Program
import socket
def main():
host = 'www.mywebsite.com'
port = 8111
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.connect((host,port))
except socket.error as e:
print(str(e))
message=input("-> ")
while message != 'q':
s.send(message.encode())
print("Sent Message")
data=s.recv(1024)
print('Recieved from server :', str (data.decode()))
message=input("->")
s.close()
if __name__ == '__main__':
main()
| Error Encountered is : [WinError 10060] |
| Python Server uses : Python 2.6.6 |
| Python Client :python 3.4 |
While using This On same system (ie: Local host as Server and client works Fine)
PS: Also link if there is any tutorial on this,Also advice some configuration if must be made.
If you want them to access each other, use public IPs. (Public IP Address) You would also need to port-forward (this is different for every router so I can't explain, look it up). Otherwise, the port you want to access will not be accessible from other networks. When you port-forward, that port on your Public IP Address can then be accessed.
Python 2 and 3 handle sockets differently! See here this question for example. What you could do as a quick workaround is to change your client start line to "#!/usr/bin/env python2.7" to force the client to use python 2 as well, that should fix your problem.
Related
I am trying to build a connection between a server and one or more clients in Python using sockets. My code works just fine when I connect with a client in the same network, but my goal is to build a program which me and my friend can use, so I want to figure out a way to connect to my server from an external network via the internet.
My server-side code looks like this:
import socket
server = "internal_ip"
port = 5006
serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
serv.bind((server, port))
print(server)
except socket.error as e:
print(e)
serv.listen(2)
while True:
conn, addr = serv.accept()
from_client = ""
while True:
data = conn.recv(4096)
if not data:
break
from_client += str(data)
print(from_client)
conn.send(str.encode("I am SERVER"))
conn.close()
print("Client disconnected")
And this is my client:
import socket
server = "internal_ip"
port = 5006
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
client.connect((server, port))
except socket.error as e:
print(e)
while True:
try:
client.send(str.encode("I am CLIENT"))
from_server = client.recv(4096)
#client.close()
print(from_server)
except:
break
client.close()
This works just fine within a network. Then I started testing the code from an external client. I changed the ip to my external ip address which I have found using whatismyipaddress.com, and port number to a different one than I use on the server side.
server = "external_ip"
port = 5007
Then I enabled port forwarding using cmd:
netsh interface portproxy add v4tov4 listenport=5007 listenaddress=external_ip connectport=5006 connectaddress=internal_ip
I get WinError 10060. Tried switching firewall on and off, and allowing these specific ports, but I can't make it work.
Can you help me with my problem please?
I know this topic is not new. There is various information out there although, the robust solution is not presented (at least I did not found). I have a P2P daemon written in python3 and the last element on the pie is to connect two clients behind the NAT via TCP. My references for this topic:
https://bford.info/pub/net/p2pnat/
How to make 2 clients connect each other directly, after having both connected a meeting-point server?
Problems with TCP hole punching
What I have done so far:
SERVER:
#!/usr/bin/env python3
import threading
import socket
MY_AS_SERVER_PORT = 9001
TIMEOUT = 120.0
BUFFER_SIZE = 4096
def get_my_local_ip():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
# doesn't even have to be reachable
s.connect(('10.255.255.255', 1))
IP = s.getsockname()[0]
except Exception:
IP = '127.0.0.1'
finally:
s.close()
return bytes(IP, encoding='utf-8')
def wait_for_msg(new_connection, client_address):
while True:
try:
packet = new_connection.recv(BUFFER_SIZE)
if packet:
msg_from_client = packet.decode('utf-8')
client_connected_from_ip = client_address[0]
client_connected_from_port = client_address[1]
print("We have a client. Client advertised his local IP as:", msg_from_client)
print(f"Although, our connection is from: [{client_connected_from_ip}]:{client_connected_from_port}")
msg_back = bytes("SERVER registered your data. Your local IP is: " + str(msg_from_client) + " You are connecting to the server FROM: " + str(client_connected_from_ip) + ":" + str(client_connected_from_port), encoding='utf-8')
new_connection.sendall(msg_back)
break
except ConnectionResetError:
break
except OSError:
break
def server():
sock = socket.socket()
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
sock.bind((get_my_local_ip().decode('utf-8'), MY_AS_SERVER_PORT))
sock.listen(8)
sock.settimeout(TIMEOUT)
while True:
try:
new_connection, client_address = sock.accept()
if new_connection:
threading.Thread(target=wait_for_msg, args=(new_connection,client_address,)).start()
# print("connected!")
# print("")
# print(new_connection)
# print("")
# print(client_address)
msg = bytes("Greetings! This message came from SERVER as message back!", encoding='utf-8')
new_connection.sendall(msg)
except socket.timeout:
pass
if __name__ == '__main__':
server()
CLIENT:
#!/usr/bin/python3
import sys
import socket
import time
import threading
SERVER_IP = '1.2.3.4'
SERVER_PORT = 9001
# We don't want to establish a connection with a static port. Let the OS pick a random empty one.
#MY_AS_CLIENT_PORT = 8510
TIMEOUT = 3
BUFFER_SIZE = 4096
def get_my_local_ip():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
# doesn't even have to be reachable
s.connect(('10.255.255.255', 1))
IP = s.getsockname()[0]
except Exception:
IP = '127.0.0.1'
finally:
s.close()
return bytes(IP, encoding='utf-8')
def constantly_try_to_connect(sock):
while True:
try:
sock.connect((SERVER_IP, SERVER_PORT))
except ConnectionRefusedError:
print(f"Can't connect to the SERVER IP [{SERVER_IP}]:{SERVER_PORT} - does the server alive? Sleeping for a while...")
time.sleep(1)
except OSError:
#print("Already connected to the server. Kill current session to reconnect...")
pass
def client():
sock = socket.socket()
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
#sock.bind((get_my_local_ip().decode('utf-8'), MY_AS_CLIENT_PORT))
sock.settimeout(TIMEOUT)
threading.Thread(target=constantly_try_to_connect, args=(sock,)).start()
while True:
try:
packet = sock.recv(BUFFER_SIZE)
if packet:
print(packet)
sock.sendall(get_my_local_ip())
except OSError:
pass
if __name__ == '__main__':
client()
Now the current code results:
./tcphole_server.py
We have a client. Client advertised his local IP as: 10.10.10.50
Although, our connection is from: [89.22.11.50]:32928
We have a client. Client advertised his local IP as: 192.168.1.20
Although, our connection is from: [78.88.77.66]:51928
./tcphole_client1.py
b'Greetings! This message came from SERVER as message back!'
b'SERVER registered your data. Your local IP is: 192.168.1.20 You are connecting to the server FROM: 89.22.11.50:32928'
./tcphole_client2.py
b'Greetings! This message came from SERVER as message back!'
b'SERVER registered your data. Your local IP is: 10.10.10.50 You are connecting to the server FROM: 78.88.77.66:51928'
As you can see the server has all information to connect two clients. We can send details about the other peer individually through the current server-client connection.
Now two questions remain in my head:
Assuming the SERVER sends information about CLIENT 1 and CLIENT 2 for each of the peers. And now the CLIENTS starts connecting like [89.22.11.50]:32928 <> [78.88.77.66]:51928 Does the SERVER should close the current connections with the CLIENTS?
How the CLIENT Router behaves? I assume it expecting the same EXTERNAL SERVER SRC IP [1.2.3.4], instead gets one of the CLIENTS EXT IP for instance [89.22.11.50] or [78.88.77.66]?
This is messier than I thought. Any help to move forward appreciated. Hope this would help other Devs/DevOps too.
Finally found the expected behavior! Don't want to give too much code here but I hope after this you will understand the basics of how to implement it. Best to have a separate file in each of the client's folder - nearby ./tcphole_client1.py and ./tcphole_client2.py. We need to connect fast after we initiated sessions with the SERVER. Now for instance:
./tcphole_client_connector1.py 32928 51928
./tcphole_client_connector2.py 51928 32928
Remember? We need to connect to the same ports as we initiated with SERVER:
[89.22.11.50]:32928 <> [78.88.77.66]:51928
The first port is needed to bind the socket (OUR). With the second port, we are trying to connect to the CLIENT. The other CLIENT doing the same procedure except it binds to his port and connects to yours bound port. If the ROUTER still has an active connection - SUCCESS.
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
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
I keep getting this error
[Errno 10061] No connection could be made because the target machine actively refused it.
I'm running Windows 7 64 bit, no virus or protection software, and python is allowed through my firewall (I've also tried turning my firewall completely off but same result). When I run the server and use telnet it connects just fine. When I try to connect to the server with the client it fails. Any suggestions as to what I could try to fix this? If you need more information just ask and I'll provide.
Client Code
import socket
import sys
def main():
host = ""
port = 8934
message = "Hello World!"
host = raw_input("Enter IP: ")
#Create Socket
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error, msg:
print "Failed to create socket. Error code: %s Error Message: %s"%(str(msg[0]),msg[1])
sys.exit()
print "Socket created"
#Connec to Server
print host
print port
s.connect((host,port))
print "You are connected to %s with IP adress of %s"%(host,host)
#Send Data
try:
s.sendall(message)
except socket.error:
print "Failed to send."
#Receive Data
reply = s.recv(4096)
if __name__ == "__main__":
main()
Server Code
# !usr/bin/python
import socket
import sys
HOST = ""
PORT = 8934
def main():
#Setup socket
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error,msg:
print "Unable to create socket"
sys.exit()
print "Socket created."
#Bind to adress
try:
s.bind((HOST,PORT))
except socket.error,msg:
print "Bind failed. Closing..."
sys.exit()
print "Socket bound."
#Start listening
s.listen(10)
print "Socket Listening"
#Accept connection
conn, addr = s.accept()
print "Connected to %s:%s"%(addr[0],addr[1])
if __name__ == "__main__":
main()
Taking a guess at your indentation, and running your codeā¦ it works just fine.* (As long as I type in 127.0.0.1 when it asks me for the IP.)
Of course the second time I run the client (if I haven't restarted the server) I get a connection-refused error. But that's just because you've coded a server that immediately quits as soon as it gets the first connection. So the second time you run the client, there is no server, so the OS rejects the connection.
You can always run the server again, which lets you run the client one more time. (Except that the server may get a 10048 error when it tries to bind the socket, because the OS is keeping it around for the previous owner. If you see that, look at SO_REUSEADDR in the docs.)
* By "works just fine" I mean that it connects, and prints out the following before quitting:
Socket created
127.0.0.1
8934
You are connected to 127.0.0.1 with IP adress of 127.0.0.1
Obviously it never sends anything to the server or receives anything back, because the server has no send or recv calls, or anything else.