How do I connect to a website port using python sockets - python

I'm coding in Python and I'm looking for a way to connect to a website port using sockets so that I can send commands to the server. My code is:
import socket
HOST = 'www.google.com'
PORT = 80
server=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((HOST, PORT))
server.listen(5)
This code is giving me an error "The requested address is not valid in its context". How do I do this?

You're trying to bind on Google's IP, which doesn't make sense because there isn't a network adapter connected to your computer with that IP (thus the error). You're mixing up creating a server and being a client connecting to a remote server. You want to connect to the Google server:
import socket
HOST = 'www.google.com'
PORT = 80
socket = socket.socket()
socket.connect((HOST, PORT))
# Send an HTTP GET request to request the page
socket.send(b"""
GET / HTTP/1.1
Host: www.google.com
""")
msg = socket.recv(8192)
print(msg)

Related

How can I use python sockets over the internet

I'm building a simple chat app using python and want to use it over the internet. The server is starting on my local machine which has the port already forwarded, and to allow other users to access I provided them with the IP address I got from www.whatismyip.com. However, every time I test the application the client side gets this error :
client_socket.connect((ip,port))
TimeoutError: [WinError 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
The server side is like this :
import socket
shost = socket.gethostname()
ip = socket.gethostbyname(shost)
port = 5000
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"Server started on {ip}:{port}")
...
And the client side :
import socket
ip = "41.102.XXX.XX"
port = 5000
username = input("Username : ").encode('utf-8')
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((ip,port))
client_socket.send(username)
...
If you are behind a router/NAT, and the PC where your server is has a LAN IP address, then you have to configure port forwarding in the router/NAT from port 5000 to port 5000 in the local IP address.
Other 2 possibilities: 1) the client is not sending the packets to the correct IP address, maybe not through the correct network interface. To check this you can use wireshark in the client machine. 2) there is some firewall rule in the server dropping the incoming messages. This is possible if you're getting the error after more than one minute. This usually happens when after the TCP SYN message there is no TCP SYN/ACK message. And not seeing the SYN/ACK is because the SYN message doesn't get to the server's listening port.

python receiving data from a friend

I'm new to this whole shazam and I'm a little confused. I want to have a server receive data on my computer, and a friend send data on his own computer. The code for my server is as follows:
import socket
HOST = 'HOST'
PORT = PORT
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
conn, addr = s.accept()
with conn:
print('Connected by', addr)
while True:
data = conn.recv(1024)
if not data:
break
conn.sendall(data)
I've blanked out the host ip and the port but I'm not really sure which one I'm supposed to be using for either tbh. The client code goes as follows
import socket
HOST = 'HOST'
PORT = PORT
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
s.sendall(b'Hello, world')
data = s.recv(1024)
print('Received', repr(data))
So my server receives it only when I run the client, not my friend. My question is what IP and ports am i supposed to use? Where can i find these numbers? Why does it only work when I run the client and how can I fix this? And if anybody can direct me to some resources about this topic I don't know what to search up :(
Thanks in advance!
The server should bind to the IP address of whatever interface it expects to receive traffic on. If it might receive traffic on multiple interfaces, you could bind to 0.0.0.0, which means 'all interfaces'. Whatever IP you decide on is what you should set for the server HOST value. For the server port, it could be a specific port or any port (port 0). Just be aware that the client will need to know which port the server is listening on.
The client should connect to the IP address or hostname and port of your server whose address is publicly accessible. This really depends on the network setup.
I suggest having your client connect to the same network as your server and trying again. If it doesn't work, make sure you're server is listening on 0.0.0.0.
If you are on different networks, these networks need to be bridged in some way.

Python3 TCP Server not seeing incoming messages from external device

I want to create a small TCP server that takes incoming TCP connections from a device that is hooked up via Ethernet to my computer.
The physical port for that has the IP 192.168.1.100 statically assigned to it.
The scripts I use as a client and server are listed at the bottom.
The setup works if I want to send messages between the python scripts. However, I am unable to receive anything from the external device (screenshot from Wireshark capture below). From what I have read I can define an interface to listen to by defining its IP. So I defined the IP of the interface as the host variable. However, I do not receive anything in my script but the messages sent by the other script. I had a similar situation already here on stackoverflow. I thought that defining the correct IP as the host would resolve this issue but it did not.
I am also having a hard time capturing the traffic between the two scripts with Wireshark at all. They did not show up anywhere.
I need to pick up these connections on the eth0 interface with the static IP 192.168.1.100:
tcp_server.py
import socket
# create a socket object
serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# get local machine name
# host = socket.gethostname()
host = "192.168.1.100"
port = 9002
# bind to the port
serverSocket.bind((host, port))
# queue up to 5 requests
serverSocket.listen(5)
while True:
# establish a connection
clientSocket, addr = serverSocket.accept()
print("Got a connection from %s" % str(addr))
msg = 'Thank you for connecting' + "\r\n"
clientSocket.send(msg.encode('ascii'))
clientSocket.close()
and this as a client:
tcp_client.py
import socket
# create a socket object
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# get local machine name
# host = socket.gethostname()
host = "192.168.1.100"
port = 9002
# connection to hostname on the port.
s.connect((host, port))
# Receive no more than 1024 bytes
msg = s.recv(1024)
s.close()
print(msg.decode('ascii'))

Connecting to a simple sockets python server remotely

I am trying to setup a very simply sockets app. My server code is:
import socket
s = socket.socket()
host = socket.gethostname()
port = 1234
s.bind((host,port))
s.listen(5) #Here we wait for a client connection
while True:
c, addr = s.accept()
print "Got a connection from: ", addr
c.send("Thanks for connecting")
c.close()
I placed this file on my remote Linode server and run it using python server.py. I have checked that the port is open using nap:
PORT STATE SERVICE
22/tcp open ssh
80/tcp open http
1234/tcp open hotline
I now run the client.py on my local machine:
import socket # Import socket module
s = socket.socket() # Create a socket object
port = 1234 # Reserve a port for your service.
s.connect(("139.xxx.xx.xx", port))
print s.recv(1024)
s.close # Close the socket when done
However I am not getting any kind of activity or report of connection. Could someone give me some pointers to what I might have to do? Do I need to include the hostname in the IP address I specify in the client.py? Any help would be really appreciated!
I've just summarize our comments, so your problem is this:
When you trying to using the client program connect to the server via the Internet, not LAN.
You should configure the
port mapping on your router.
And however, you just need configure the
port mapping for your server machine.
After you did that, then you can use the client program connect to your server prigram.

UDP client cannot talk through an external IP address

I am running a UDP server and client (python). When within the same local network, the client is able to talk to the server. However when the server IP address is set to IP address of the router (which has UDP port forwarding to the server), the client is not able to talk with the server at all. I am wondering if anyone can point out why this works within the local network (on different machines) but I cannot make the client connect to the server using external IP address of the router to which both the client and server are connected.
The code for the client
import socket
import sys
HOST, PORT = "<IP address of router which is port forwarded to server>", 5000
data = " Hello from Client" #.join(sys.argv[1:])
# SOCK_DGRAM is the socket type to use for UDP sockets
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# As you can see, there is no connect() call; UDP has no connections.
# Instead, data is directly sent to the recipient via sendto().
sock.sendto(data + "\n", (HOST, PORT))
received = sock.recv(1024)
print "Sent: {}".format(data)
print "Received: {}".format(received)
Code for the server
import SocketServer
class MyUDPHandler(SocketServer.BaseRequestHandler):
def handle(self):
data = self.request[0].strip()
socket = self.request[1]
print "{} wrote:".format(self.client_address[0])
print data
socket.sendto(data.upper(), self.client_address)
if __name__ == "__main__":
HOST, PORT = "<local IP address of server", 5000
server = SocketServer.UDPServer((HOST, PORT), MyUDPHandler)
server.serve_forever()
OK i figured out what was going on.
Router is connected to two computers - Computer A and Computer B. Computer A can talk to Computer B using the local network (UDP server client). However when Computer A (UDP client) sends data to Computer B (UDP server) using the Router IP address (external IP address) with the router port forwarding to Computer B, it was not working. Apparently the server will only accept connections that originate outside the local network when the client uses the external IP address

Categories

Resources