socket.gaierror: [Errno 11001] getaddrinfo failed while connecting to ngrok server - sockets

I wrote a simple server code using socket module forward the listening port using ngrok but when i try to connect to ngrok provided url it gives error
socket.gaierror: [Errno 11001] getaddrinfo failed
Server Code
import socket
server = socket.socket()
host = "localhost"
port = 5002
server.bind((host,port))
print("Started Listening.........")
server.listen()
con, addr = server.accept()
print("Connection is accepted from :",str(addr))
while True:
data = con.recv(1024).decode()
if not data:
break
print("From Connected User :",str(data))
data = str(data).upper()
print("Received from User: " + str(data))
data = input("Enter message::::")
con.send(data.encode())
con.close()
Client Code
import socket
host = "tcp://0.tcp.in.ngrok.io:18376"
port = 5002
client = socket.socket()
client.connect((host,port))
mess = input("Enter message::")
while mess!='q':
client.send(mess.encode())
data = client.recv(1024).decode()
print("FROM SERVER = ",data)
mess = input("Enter message ::")
client.close()
I am creating a tcp tunnel using ngrok at 5002 port
ngrok tcp 5002
It generates
Web Interface http://127.0.0.1:4040
Forwarding tcp://0.tcp.in.ngrok.io:18376 -> localhost:5002
i am using this tcp url in my client host code host = "tcp://0.tcp.in.ngrok.io:18376" I tried removing port number and tried only tcp://0.tcp.in.ngrok.io but nothing happend
Can you guide me how to connect to this tcp tunnel from socket module because i am pretty new to socket programming.

Related

Socket Programming: Setup server, it runs if port is 80, but cannot run if port is other

I'm trying to setup a server using Python socket programming, using the code below:
from socket import *
serverPort = 80
serverSocket = socket(AF_INET, SOCK_STREAM)
serverSocket.bind(("", serverPort))
serverSocket.listen(1)
print ("The server is ready to receive")
while True:
connectionSocket, addr = serverSocket.accept()
sentence = connectionSocket.recv(1024).decode()
capitalizedSentence = sentence.upper()
connectionSocket.send(capitalizedSentence.encode())
connectionSocket.close()
When I use this code and try to enter localhost in a web browser, I get the response without any problem as shown.
But, when I change line 3 in the code to serverPort = 12000 and try to enter localhost:12000, I don't get a response.
Note: I use Windows not Linux, and I run the Python code on PyCharm 2020.3.3.
Neither example should be working, regardless of the port used, because the server is not sending back a valid HTTP response, like the error message says. The fact that the 1st example "works" is a fluke.
Try this instead:
from socket import *
serverPort = 80
serverSocket = socket(AF_INET, SOCK_STREAM)
serverSocket.bind(("", serverPort))
serverSocket.listen(1)
print ("The server is ready to receive")
while True:
connectionSocket, addr = serverSocket.accept()
sentence = connectionSocket.recv(1024).decode()
capitalizedSentence = sentence.upper()
reply = "HTTP/1.0 200 OK\r\nConnection: close\r\n\r\n"
connectionSocket.send(reply.encode()) # <-- add this!
connectionSocket.send(capitalizedSentence.encode())
connectionSocket.close()

Connecting two computers in different networks using socket and Port forwarding

I have set up a simple client-server communication code and it works well in my computer when my computer itself acts as a server and the client.
Now I am trying to run this same code on two different computers in different networks( different locations) where my computer will act as a server and my friend's computer as a client.
I have done port forwarding in my router as well as in my friend's router for the port which we are trying to communicate. We both have set up a static IP in our internal network behind the router. We both had shutdown the firewall while running the code.
I am running my code on Jupiter notebook and the same is my friend too.
here is my server code:
import socket
import threading
HEADER = 64
PORT = 5064
SERVER = '0.0.0.0'
ADDR = (SERVER, PORT)
FORMAT = 'utf-8'
DISCONNECT_MESSAGE = "quit"
Receive_from_client = "get info"
server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server.bind(ADDR)
def handle_client(conn, addr):
print("\n" + f"[NEW Connection] detected from IP: {addr[0]} & Port:{addr[1]} ")
conn.send(f"connected to server {ADDR}".encode(FORMAT))
connected =True
while connected:
msg_length = conn.recv(HEADER).decode(FORMAT) # decode the msg from byte to utf-8 format
if msg_length:
msg_length = int(msg_length)
msg = conn.recv(msg_length).decode(FORMAT)
if msg == DISCONNECT_MESSAGE:
connected = False
print(f" [Client][{addr}] {msg}")
print("Your session is disconnected")
break
if msg == Receive_from_client:
print("\n" + f"Send your msg to client with IP: {addr[0]}")
thread = threading.Thread(target = send2client, args = (conn, addr))
thread.start()
print(f" [Client][{addr}] {msg}")
conn.send(f"Msg received by server with IP:{addr[0]}".encode(FORMAT))
conn.close()
server.close()
def start():
server.listen()
print("\n"+ f"[LISTENING] Server is listening from IP: {SERVER} ")
while True:
conn, addr = server.accept()
thread = threading.Thread(target = handle_client, args = (conn, addr))
thread.start()
Here is the client code
import socket
import threading
HEADER = 64
PORT = 5064
FORMAT = 'utf-8'
DISCONNECT_MESSAGE = "quit"
SERVER = '103.192.207.250' # SERVERS public IP
ADDR = (SERVER, PORT)
client = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
client.connect(ADDR)
def send2server():
while True:
msg = input()
message = msg.encode(FORMAT)
msg_lenght = len(message)
send_length = str(msg_lenght).encode(FORMAT)
send_length += b' '*(HEADER - len(send_length))
client.send(send_length)
client.send(message)
print(client.recv(2048).decode(FORMAT))
if msg == DISCONNECT_MESSAGE:
print("session closed")
client.close()
def start():
print("\n"+ f"[LISTENING] client is listening from IP: {ADDR} ")
send2server()
I have opened the port by going on windows firewall defender and selecting new inbound and outbound rules to open 5064 TCP port.
but still, the code doesn't works..
my server keeps waiting for connection and the client-side after few seconds of running gives this error:
TCP error code 10060: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
Even while my server is listening from port 5064 when I scan this port to check if the port is open or not it says closed.
How do I check if the port I have forwarded is for sure open and also how do I get this thing work?
I have tried all of this and if there is any other thing I am missing please tell. I am struggling to get this work for the past 3 days.

Qpython, socket connection error

I'm learning server- and client-side connections:
What I'm attempting to do is connecting server- and client-side scripts with each other on Qpython(android)
The problem is when I run it, it gives me this:
"ConnectionRefusedError: Errno [111] Connection Refused"
When I run the same scripts on my computer it gives me no error.
Background information:
I'm using 2 different apps on my phone
And 1 on my computer.
But I suppose that can't be the problem
Client
import socket
import sys
HOST, PORT = "localhost", 9999
Data = " ".join(sys.argv[1:]) + input(" Enter Message:\n"
# Create a socket (SOCK_STREAM means a TCP socket)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
# Connect to server and send data
sock.connect((HOST, PORT))
sock.sendall(bytes(data + "\n", "utf-8"))
# Receive data from the server and shut down
received = str(sock.recv(1024), "utf-8")
finally:
sock.close()
print("Sent: {}".format(data))
print("Received: {}".format(received))
Server
import socketserver
class MyTCPHandler(socketserver.BaseRequestHandler):
def handle(self):
# self.request is the TCP socket connected to the client
self.data = self.request.recv(1024).strip()
print("{} wrote:".format(self.client_address[0]))
print(self.data)
# just send back the same data, but upper-cased
self.request.sendall(self.data.upper())
if __name__ == "__main__":
HOST, PORT = "localhost", 9999
# Create the server, binding to localhost on port 9999
server = socketserver.TCPServer((HOST, PORT), MyTCPHandler)
server.serve_forever()

CFSocket created in Swift not listening

I'm trying to get basic Bonjour discovery up and running using the sample code from a 2012 WWDC session, but having converted it to Swift. It's partially working. I am able to register a port, and register my service on that port. The client is able to discover that service, and resolve it.
Here's the issue: I call CFSocketCreateWithNative() and specify the callback listener, but that callback never gets called. Further, I tried connecting wiht telnet (telnet localhost 12345) and I get:
Trying ::1...
telnet: connect to address ::1: Connection refused
Trying 127.0.0.1...
telnet: connect to address 127.0.0.1: Connection refused
Trying fe80::1...
telnet: connect to address fe80::1: Connection refused
telnet: Unable to connect to remote host
This is an abbreviated version of how I'm registering the sockets, with the full Swift file in a Gist:
private func registerIPv4Socket() throws -> (Int32, in_port_t) {
let fd4 = socket(AF_INET, SOCK_STREAM, 0)
var sin = sockaddr_in()
sin.sin_family = sa_family_t(AF_INET)
sin.sin_len = UInt8(sizeofValue(sin))
sin.sin_port = 0
withUnsafePointer(&sin) {
Foundation.bind(fd4, UnsafePointer($0), UInt32(sin.sin_len))
}
var addrLen = socklen_t(sizeofValue(sin))
withUnsafeMutablePointers(&sin, &addrLen) { (sinPtr, addrPtr) -> Int32 in
getsockname(fd4, UnsafeMutablePointer(sinPtr), UnsafeMutablePointer(addrPtr))
}
let listenError = listen(fd4, 5)
return (fd4, sin.sin_port)
}
private func registerIPv6Socket(port: in_port_t) throws -> Int32 {
let fd6 = socket(AF_INET6, SOCK_STREAM, 0)
var one: Int32 = 1
withUnsafePointer(&one) {
setsockopt(fd6, IPPROTO_IPV6, IPV6_V6ONLY, UnsafePointer($0), socklen_t(sizeofValue(one)))
}
var sin6 = sockaddr_in6()
sin6.sin6_family = sa_family_t(AF_INET6)
sin6.sin6_len = UInt8(sizeofValue(sin6))
sin6.sin6_port = port
withUnsafePointer(&sin6) {
Foundation.bind(fd6, UnsafePointer($0), UInt32(sin6.sin6_len))
}
var addrLen = socklen_t(sizeofValue(sin6))
withUnsafeMutablePointers(&sin6, &addrLen) { (sinPtr, addrPtr) -> Int32 in
getsockname(fd6, UnsafeMutablePointer(sinPtr), UnsafeMutablePointer(addrPtr))
}
listen(fd6, 5)
return fd6
}
Why isn't my app listening on the port it's reporting it should be?
Your IPv4 socket is listening on port sin.sin_port.bigEndian, but your IPv6 socket is listening on the little endian port. Update your IPv6 code to use the big endian port:
sin.sin6_port = port.bigEndian

Destination Unreachable (Port Unreachable) using Haskell

Using Wireshark to debug, I receive the following error when sending UDP packets on localhost:
Destination Unreachable (Port Unreachable)
Checksum: 0x0000 (Illegal)
I am constructing my server first on a port between 10000 - 15000 using
startServer :: Port -> IO Server
startServer port = withSocketsDo $ do
-- Look up the server address and port information.
addrs <- getAddrInfo (Just $ defaultHints { addrFlags = [AI_PASSIVE] }) Nothing (Just port)
let serverAddress = head addrs
-- Bind to the socket.
sock <- socket (addrFamily serverAddress) Datagram defaultProtocol
bindSocket sock (addrAddress serverAddress)
-- Create the server and run the client send and receive threads.
clients <- newMVar $ createEmptyClients
let server = Server sock port clients
_ <- forkIO $ forever $ receiveClientJoin server
return server
I am listening for new clients connecting via UDP using
-- | Connected a client to the server.
receiveClientJoin :: Server -> IO ()
receiveClientJoin server = do
print "Receiving"
(msg, _, clSockAddr) <- recvFrom (sSocket server) 4096
print $ "Server received client join message: " ++ msg
And I am connecting to the server with clients using
connectToServer port = do
-- Get the server's address and port information.
addrInfo <- getAddrInfo Nothing (Just "localhost") (Just port)
let serverAddr = head addrInfo
sock <- socket (addrFamily serverAddr) Datagram defaultProtocol
sendTo sock "Hello from this client!" (addrAddress serverAddr)
Why are my clients' packets not finding the server?
The problem is you are listening on an IPv6 address and trying to connect to an IPv4 address. This is actually a slightly common problem. For example, I ran across this issue when working with commsec.
Consider the fragments where you discover your AddrInfo:
import Network.Socket
main :: IO ()
main = do
let port = "2474"
addrs <- getAddrInfo (Just $ defaultHints { addrFlags = [AI_PASSIVE] }) Nothing (Just port)
let serverAddress = head addrs
print serverAddress
addrInfo <- getAddrInfo Nothing (Just "localhost") (Just port)
let serverAddr = head addrInfo
print serverAddr
Now the output will vary by machine, but on one of my CentOS systems with both IPv4 and IPv6 addresses the output clearly shows the second (connect) address is IPv6 while the first (listen) address is IPv4:
AddrInfo {addrFlags = [AI_PASSIVE], addrFamily = AF_INET, addrSocketType = Stream, addrProtocol = 6, addrAddress = 0.0.0.0:2474, addrCanonName = Nothing}
AddrInfo {addrFlags = [AI_ADDRCONFIG,AI_V4MAPPED], addrFamily = AF_INET6, addrSocketType = Stream, addrProtocol = 6, addrAddress = [::1]:2474, addrCanonName = Nothing}
One solution is to force a particular version of IP via a hint or an address (ex. an IPv4 address as in my comment). The hint solution is probably more desirable:
-- For servers:
addrs <- getAddrInfo (Just defaultHints { addrFamily = AF_INET6
, addrFlags = [AI_PASSIVE] })
Nothing (Just port)
-- For clients:
addrInfo <- getAddrInfo (Just defaultHints { addrFamily = AF_INET6 })
(Just "localhost") (Just port)