Reputation: 1032
Background:
I am programming a chat server application in Python that uses AES encryption for messages. When a client wishes to send a message, the message is encrypted, sent to a central server, and then broadcast to all other clients. Since each client has specified a secret key upon joining the application, all incoming messages to a client are decrypted using this secret key (the same key used to encrypt messages before sending them). Thus, any two clients which joined the chatroom using the same secret key can communicate securely. Messages sent by users which joined using different secret keys will have been decrypted improperly, and thus still look like gibberish. This part works!
Problem:
I would like the application to also display the IP address of a user next to a message sent by them. For example, something like <user1_ip> hello there, user2!
. Unfortunately, when I try sending this data using send()
and recv()
, I am unable to send the IP address information separately from the message. Due to buffering, both strings are received as one concatenated string. Both strings are of variable length, and I can't separate the two using a regular expression because I have no idea what data the message will contain. I have tried setting socket options such as TCPNO_DELAY
to separate the two and have looked through the docs quickly, but no possible solutions jumped out at me. There must be some simple solution which I am missing or unaware of, and I would greatly appreciate any guidance!
Upvotes: 1
Views: 249
Reputation: 604
The IP addresses (I assume you are dealing with IPv4) have a maximum length of 15 characters. In the case where you have something like 192.128.1.1 just add preceding zeros and turn it to 192.128.001.001 - that way you get to a fixed length. You send the IP first, then the message. On the receiving side you can strip those zeros away.
Alternatively, add a single-byte header that will specify the length of the IP address.
Another solution is to introduce a delay of a few seconds between the send() statements, for example:
conn.send(ip_addr)
time.sleep(3)
conn.send(msg)
Or just send the IP address as the first 4 bytes, unless you have a reason to send the IP address a string.
Upvotes: 1