David
David

Reputation: 983

Python sockets: How do I get the address a client is connected to?

I have some code that hosts a local server and when a user connects it will send them some html code, which works fine. But I want it so if they connect to http://localhost:90/abc it will show something different. How can I get the exact url they connected to?

Here is my code:

import socket

sock = socket.socket()
sock.bind(('', 90))
sock.listen(5)

print("Listening...")

while True:

    client, address = sock.accept()

    print("Connection recieved: ", address)
    print(The exact url they connected to.)
    print()

    client.send(b'HTTP/1.0 200 OK\r\n')
    client.send(b"Content-Type: text/html\r\n\r\n")
    client.send(b'<html><body><h1>Hello, User!</body></html>')
    client.close()


sock.close()

I tried print(client.getpeername()[1]), but that gets the client ip, and if there is a similar way to get the ip they connected to it probably wont get the 'abc' part of the url.

Thanks in advance.

Upvotes: 0

Views: 7216

Answers (2)

Barmar
Barmar

Reputation: 782488

When the client connects to your server, it will send:

GET /abc HTTP/1.1
Host: localhost
more headers...
<blank line>

Your server needs to parse the GET line and extract /abc from that.

Upvotes: 1

Alex Sherman
Alex Sherman

Reputation: 524

Socket's don't have a notion of URL, that's specific to the HTTP protocol which runs on top of a socket. For this reason, only part of the HTTP URL is even used in the creation of a socket.

|--1---|----2----|-3-|--4-|
http:// localhost :90 /abc
  1. Specifies which protocol inside of TCP the URL uses
  2. Specifies the remote host, either by IP address or hostname
  3. Specifies the remote port and is optional
  4. Specifies the path of the URL

Only parts 2 and 3 are actually known to a TCP socket though! This is because TCP is a very basic form of communication, HTTP adds a bunch of functionality on top of it like requests and responses and paths and so on.

Basically if you're implementing an HTTP server, knowing the /abc part is your job. Take a look at this example. The client actually sends the /abc part to the server, otherwise it has no way of knowing which path the request is for.

Upvotes: 3

Related Questions