Tag Archives: socket

Simple group messenger/chat in Python

Aaaaannd here is another post of mine on sockets, client/server models and stuff. I suppose you have started to get bored by the same stuff everyday right? Seems like I just can’t get enough of this thing. But trust me, I had no intention of doing this today, a friend of mine instigated me write a messenger for a project we were working on, and it turned out, writing this simple messaging program was more interesting than I thought.

So, instead of creating a straight forward chat program that was ‘actually’ required by my friend, I created this ‘one-server-multiple-clients’ program, which is more like the real world chat apps we use everyday.

To run the program, execute the ‘server.py’ (after changing the bind() address to the address of the server on which it is supposed to run). Then, execute the ‘client.py’ (guess what? same thing here. But you will have to add the server address in the connect() function here). Of course, you can have all of them running on the same system, but there ain’t any fun in it, right?

Last but not the least, I have commented as much as I could, unlike my last article, so I expect everyone reading this, with a bit of programming knowledge, will understand this straight forward code.

server.py

# Import the necessary libraries
import socket
import sys
import select
# Take message from an host and send it to all others
def shout(sock, message):
  for socket in LIST:
    try:
      # Don't send it back to server and yourself!
      if socket != serv and socket != sock:
        socket.send(message)
    except:
      # Assume client has got disconnected and remove it.
      socket.close
      LIST.remove(socket)
# Declare variables required later.
# To store list of sockets of clients as well as server itself.
LIST = []
# Common buffer for all purposes
buff = 1024
# Declaration of Server socket.
serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
serv.bind(("192.168.1.10", 1356))
# Listen for upto 6 clients. Increase if you need more.
serv.listen(6)
# Add server socket to the LIST
LIST.append(serv)
while 1:
  # Moniter clients all simultaneously
  reads, writes, err = select.select(LIST, [], [])
  for sock in reads:
    # A new client connected?
    if sock == serv:
      sockfd, addr = serv.accept()
      LIST.append(sockfd)
    # Naah, just a new message!
    else:
      try:
        # Get his shitty message.
        data = sock.recv(buff)
        if data:
          # If he wrote something, send it to shout() function for broadcast.
          shout(sock, data)
      except:
        # Shit just got real. Client kicked by server :3
        sock.close()
        LIST.remove(sock)
        # Do this till the end of time.
        continue
serv.close()

client.py

# Import the nessary libraries
import socket
import string
import select
import sys

# Socket variable declaration
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(2)

# Connect to server. Change this for remote servers.
s.connect(("192.168.1.10", 1356))

# A prompt asking client to enter something.
sys.stdout.write(">")
sys.stdout.flush()

while 1:
  # These are the possible events.
  # sys.stdin --> Client has typed something through keyboard.
  # s --> Server has send a new message by some other client you.
  streams = [sys.stdin, s]

  # Moniter both the streams simultaneously for inputs.
  readable, writable, err = select.select(streams, [], [])

  # If server has sent something, readable will fill up.
  for sock in readable:
    if sock == s:

      # Receive data in our variable. Check if it is empty.
      data = sock.recv(1024)
      if not data:
        sys.exit()
      else:

        # Write data to stdout and give client prompt back.
        sys.stdout.write(data)
        sys.stdout.write(">")
        sys.stdout.flush()

    # No, its not the server. Our client has typed something in.
    else:

      # Read message. Send it to server. Give prompt back to client.
      msg = sys.stdin.readline()
      s.send(msg)
      sys.stdout.write(">")
      sys.stdout.flush()

So that was the code. Here is a glimpse of the output. The server is running off my ‘raspberrypi’ and all clients are running on my computer. Looks cool right?

If you look closely, one of the clients missed a message sent by another client, LOL, so that is normal. Any suggestions or edits or corrections, drop them in the comments below. 🙂

Python vs C – How simple is it to write a pair of communicating sockets?

Lately I have been reading a lot of articles online written to compare Python to other languages. It is not a secret to anyone that the Python community is growing, and along with it, is the number of people who promote/recommend this language, of course.

Let me not add up to the already large mass of those articles by boasting about Python’s usability, speed and practicality, but rather, I will compare the two languages by writing a small socket client/server pair in each of those languages.

But first, let me give you some of my personal opinions about both the languages since I know them well enough. C is very dear to me, not only because it was the first language I had ever learnt, but also because it runs most of the GNU, and GNU is well, very dear to me! C also happens to be my only second language of choice, after Python (although I know bits of Java, I prefer not to use it, not sure why, but I hate it). I have been programming in Python only from the last couple of months and I was really impressed. I solve HackerEarth and CodeChef problems as a pass time. Although I could do all of the problems I have done in C, doing them in Python took like 1/10th of the time (literally!) and 1/10th the typing effort. I would admit, C is much more fun to write than Python, simply because you ‘feel’ the code is yours, and I love to code C whenever I am free, will I use it in an environment where time is the priority? Probably not. Maybe when C is the only way out, but most of the time, I am better off writing it in Python.

That being said, the popularity of C doesn’t get any less, and it is going to stay that way as long as, maybe the Internet. Here’s something I found.

https://www.tiobe.com/index.php/content/paperinfo/tpci/index.html
You see the thing on top there? Yes, it is there for a reason. To make it short, C is powerful, very powerful. C gives you access to things you can not really imagine in other languages. On the other hand, Python is practical, flexible, and easy to learn. Web apps, sockets, Raspberry Pi, Arduino, Android or anything else you can imagine, there has to be a library made for it by someone, somewhere.

The code part.

I am giving the client and server code in both the languages here as is. No explanation and stuff, because that’s not the topic here. Note that all the source codes are tested running OK on Kali 1.0.6, gcc and all stock stuff, so it should be not much trouble to get it running. Windows guy, search for gcc directory and run it over the command prompt. It won’t run from any IDE.

Python

Writing a pair of communicating TCP sockets require around 30 minutes along with the understanding part, if you have got some background in networking. Python does most of the stuff for you, and you just create a socket variable, supply host and port and that’s it. Rest is left to your imagination (or not, I got too carried away!). Here comes the code:
client.py

import socket
s = socket.socket()
host = socket.gethostname()
port = 1356 
s.connect((host, port))
shit = s.recv(1024)
print shit
s.close()
server.py

s = socket.socket()
host = socket.gethostname()
s.bind((host, 1356))
s.listen(5)
while True:
    c, addr = s.accept()
    c.send("Message from server")
    c.close()

And that is it. Even if it looks lame (which it is), it is the maybe the simplest thing that qualifies to be called a server/client.

C

Now lets write the same in C. This is around 4 times the size of Python code, and much of the stuff are done by hand (nothing new for C, I suppose). This code is the shortest I could cut it to, and just does one simple task. Sends the “Client talking loud!\n” message to server over port 1356 on localhost. The parameters can be edited as per convenience to suit any inter network testing, but that’s the most this code will do. Nevertheless, this is a TCP client/server model.
client.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <unistd.h>

int main(int argc, char **argv) {
int sock, port, n;
struct sockaddr_in serv_addr;
struct hostent *server;
char buffer[256];
port = atoi("1356");
sock = socket(AF_INET, SOCK_STREAM, 0);
server = gethostbyname("127.0.0.1");
bzero((char *)&serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length);
serv_addr.sin_port = htons(port);
connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr));
bzero(buffer, 256);
strcpy(buffer, "Client talking loud!\n");
write(sock, buffer, strlen(buffer));
close(sock);
}

server.c

#include <stdio.h> 
#include <strings.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>


int main(int argc, char **argv) {
int sock, nsock, port;
socklen_t clilen;
char buffer[256];
struct sockaddr_in serv_addr, cli_addr;
sock = socket(AF_INET, SOCK_STREAM, 0);
bzero((char*)&serv_addr, sizeof(serv_addr));
port = atoi("1356");
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(port);
bind(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr));
listen(sock, 2);
clilen = sizeof(cli_addr);
nsock = accept(sock, (struct sockaddr *)&cli_addr, &clilen);
bzero(buffer, 256);
read(nsock, buffer, 255);
printf("%s\n", buffer);
close(sock);
close(nsock);
}

Here is the expected output:

Sorry, there is no commenting in the above code, and it really needs some explanation. I would’ve written them, but then, the code would have grown three folds (LOL)! It will need another nice article to explain all the stuff from that client.c and server.c code. I will conclude here. Thank you for reading 🙂

Update: If you happen to run any of the above code, make sure you run server first!

Simple TCP banner grabber in C

Hello folks, Its been a great week. I got the book called Expert C Programming – Deep C Secrets, by Peter van der Linden. I read about 100 pages in a couple of days, and I had never gained so much confidence reading any other book. Many concepts got sharper, doubts cleared and confidence boasted. A must read book if you know some C and want to understand the nuts and bolts of it.

In the same wave, I decided to write a small utility with sockets later today. It went great. Lots of coding, googling (I just can’t code without Google, maybe a sign of newbie) and debuging. Finally I ended up having a program that was partially correct. It works, but it doesn’t. It actually does more than what is told, and I couldn’t find out why. Still, I am posting it here, for those interested. Please correct it, as I didn’t really get what is wrong with it. Looks like some of the array locations are interpreted as ports, in the ‘ports’ array.

usage example: ./scanner 192.168.1.2 22,80,443

 root@kali:~/Desktop/C/socket# ./client 192.168.1.10 22,80

[+]Testing port: 22
[*]SSH-2.0-OpenSSH_6.0p1 Debian-4

[+]Testing port: 80
[*]<!DOCTYPE HTML PUBLIC “-//IETF//DTD H

TML 2.0//EN”>
<html><head>
<title>501 Method Not Implemented</title>
</head><body>
<h1>Method Not Implemented</h1>
<p>garbage to /index.html not supported.<br />
</p>
<hr>
<address>Apache/2.2.22 (Debian) Server at 127.0.1.1 Port 80</address>
</body></html>

[+]Testing port: 4195840
[-]Error Connecting to port

[+]Testing port: 0
[-]Error Connecting to port

[+]Testing port: 1476291006
[-]Error Connecting to port

[+]Testing port: 32767
[-]Error Connecting to port

I am not sure what that is, the part after the actual banner I mean. I will update this article as soon I get things sorted. Here is the code, if anyone wants to have a look.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>

void scanner(int port, char host[]);

int main(int argc, char **argv) {
char host[100];
char *p;
int ports[10];
int i = 0;
int var;
char tok[] = " ,";

if (argc < 2) {
fprintf(stderr,"[+]usage: %s <hostname> <port,port,port...>n", argv[0]);
exit(0);
}

p = strtok(argv[2], tok);
strcpy(host, argv[1]);
while(p != NULL) {
sscanf(p, "%d", &var);
ports[i++] = var;
p = strtok(NULL, tok);
}

for(i=0; i<(sizeof(ports)/sizeof(ports[0])); i++) {
fprintf(stdout, "n[+]Testing port: %dn", ports[i]);
scanner(ports[i], host);
}
return 0;
}

void scanner(int port, char host[]) {

int sock, n;
struct hostent *server;
struct sockaddr_in serv_addr;

char buffer[4096];

server = gethostbyname(host);

sock = socket(AF_INET, SOCK_STREAM, 0);
/* Edit the params of socket to scan UDP ports,
* should be pretty straight forward I suppose.
*/

if(sock < 0) {
fprintf(stderr, "[-]Error creating socket");
return;
}

bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
// AF_UNIX for Unix style socket

bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length);
serv_addr.sin_port = htons(port);

n = connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr));
sleep(2);
if(n < 0) {
fprintf(stderr, "[-]Error Connecting to portn");
return;
}

memset(buffer, 0, sizeof(buffer));
strcpy(buffer, "garbagern");

n = write(sock, buffer, strlen(buffer));
if(n < 0) {
fprintf(stderr, "[-]Error writing (Port closed maybe?!)n");
return;
}

bzero(buffer, 4096);
n = read(sock, buffer, 4096);
if(n < 0) {
fprintf(stderr, "[-]Error reading (Port closed maybe?!)n");
return;
}

fprintf(stdout,"[*]%sn", buffer);
close(sock);

}