Categories
Programming

GST(Indian) check digit validation algorithm2 min read

GST number validation is done through 2 steps

  1. Check if there is a character in position of a character and a number in position of a number.
  2. Validate the check digit that is the last character in the GST no. with  Luhn mod N algorithm (https://en.wikipedia.org/wiki/Luhn_mod_N_algorithm)

An implementation in javascript

let GST = {
  /*
      Luhn mod N algorithm    
      https://en.wikipedia.org/wiki/Luhn_mod_N_algorithm
  */
  chars: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ',
  pattern: /[0-9]{2}[a-zA-Z]{5}[0-9]{4}[a-zA-Z]{1}[1-9A-Za-z]{1}[Zz1-9A-Ja-j]{1}[0-9a-zA-Z]{1}/,

  generate_check_charcter: function(input) {
    factor = 2;
    sum = 0;
    n = this.number_of_valid_input_chars();

    for (i = input.length - 1; i >= 0; i--) {
      code_point = this.code_point_from_char(input[i]);
      addend = factor * code_point;

      factor = (factor == 2) ? 1 : 2;

      addend = (addend / n) + (addend % n);
      sum += Math.floor(addend);
    }

    remainder = sum % n;
    check_code_point = (n - remainder) % n;

    return this.char_from_code_point(check_code_point);
  },

  validate_check_character: function(input) {
    factor = 1;
    sum = 0;
    n = this.number_of_valid_input_chars();

    for (i = input.length - 1; i >= 0; i--) {
      code_point = this.code_point_from_char(input[i]);
      addend = factor * code_point;

      factor = (factor == 2) ? 1 : 2;

      addend = parseInt(addend / n) + (addend % n);
      sum += addend;
    }

    remainder = sum % n;

    return (remainder == 0);
  },

  number_of_valid_input_chars: function() {
    return this.chars.length;
  },

  code_point_from_char: function(input) {
    let str = this.chars;
    for (let i = 0, q = str.length; i < q; i++) {
      if (input == str[i]) {
        return i;
      }
    }
  },

  char_from_code_point: function(input) {
    let str = this.chars;
    for (let i = 0, q = str.length; i < q; i++) {
      if (input == i) {
        return str[i];
      }
    }
  },

  /*
      Function called to check if a GSTno is valid.
      Full GST.no is passed to the func
  */
  is_valid_num: function(gst_no) {
    //Check for pattern
    var patt = new RegExp(this.pattern);
    if (!patt.test(gst_no)) {
      console.log('pattern wrong');
      return false;
    }

    //Validate the check digit
    return this.validate_check_character(gst_no);
  }

};

USAGE:

GST.is_valid_num(gst_no);

true  is returned if the GST.no is valid. false  if not.

Comment below if you have any questions.

Categories
Programming

C TCP Server in Windows – Thread per connection2 min read

A simple TCP server in C (windows). It works in a “thread per connection” way.

Note- I don’t know what I am doing.

#include <winsock.h> 
#include <stdio.h> 
#include <string.h> 
#include <sys/types.h>

#define PORT 50001

//Function that threads run
static DWORD __stdcall func(int s);

int main() {
  //Dont ask just put it in there
  WSADATA wsaData;
  if (WSAStartup(MAKEWORD(2, 0), & wsaData) != 0) {
    fprintf(stderr, "WSAStartup failed.\n");
    exit(1);
  }

  //Socket initiation
  int sock;
  if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) {
    printf("Socket initiation failed!");
    return 0;
  }

  //Socket settings
  struct sockaddr_in addr;
  addr.sin_family = AF_INET;
  addr.sin_port = htons(PORT);
  addr.sin_addr.s_addr = inet_addr("127.0.0.1");
  memset(addr.sin_zero, '\0', sizeof addr.sin_zero);

  //Bind the socket
  int b;
  if ((b = bind(sock, & addr, sizeof(addr))) == SOCKET_ERROR) {
    printf("Socket initiation failed!");
    return 0;
  }

  //Listen on socket
  int l = listen(sock, 25);

  printf("TCP server listening on port %d\n", PORT);

  //If (con) pass it to a new thread 
  while (1) {
    struct sockaddr_in client_addr;
    unsigned int c_len = sizeof client_addr;
    int s1 = accept(sock, & client_addr, & c_len);
    unsigned int cur_tid;

    _beginthreadex(NULL, 0, func, s1, 0, & cur_tid);
  }

  //Cleanup
  closesocket(sock);
  WSACleanup();
  return 0;
}

static DWORD __stdcall func(int s) {
  puts("Connection accepted");

  //Read data from client
  char buff[1024];
  unsigned int tot_bytes = recv(s, buff, sizeof(buff), MSG_PEEK);
  char * client_data = (char * ) malloc(tot_bytes + 1);
  for (int i = 0; i < (tot_bytes); i++) {
    client_data[i] = buff[i];
  }
  client_data[tot_bytes] = '\0';

  printf("Msg from client: %s\n", client_data);

  //Pretend you are processing info
  puts("Processing req");
  Sleep(5000);
  puts("Processing complete");

  //Prepare message for the client
  char * message;
  if (strcmp(client_data, "COMMAND1") == 0) {
    char lmsg[] = "COMMAND1 recieved";
    message = (char * ) malloc(strlen(lmsg));
    message = lmsg;
  } else if (strcmp(client_data, "COMMAND2") == 0) {
    char lmsg[] = "COMMAND2 recieved";
    message = (char * ) malloc(strlen(lmsg));
    message = lmsg;
  } else {
    char lmsg[] = "NO COMMAND recieved";
    message = (char * ) malloc(strlen(lmsg));
    message = lmsg;
  }

  free(client_data);

  //Send data to client
  send(s, message, strlen(message), 0);

  return 0;
}

TCP client in Node.js

var net = require('net');

var client1 = new net.Socket();
client1.connect(50001, '127.0.0.1', function() {
  console.log('Connected');
  client1.write('COMMAND1');
});

client1.on('data', function(data) {
  console.log('Received on 1: ' + data);
  client1.destroy();
});

client1.on('close', function() {
  console.log('Connection closed on 1');
});

var client2 = new net.Socket();
client2.connect(50001, '127.0.0.1', function() {
  console.log('Connected on 2');
  client2.write('COMMAND2');
});

client2.on('data', function(data) {
  console.log('Received on 2: ' + data);
  client2.destroy();
});

client2.on('close', function() {
  console.log('Connection closed on 2');
});

See single threaded windows TCP server using IO Completion Ports – https://github.com/hrishimk/iocp_tcp_server

Categories
Programming

Learning something new : RUST lang PART 32 min read

Error Handling

In the previous one where we built a guess the number game in rust, we did not handle any errors. The obvious error was that if something other than a number was inputted the program would crash.

Now that I have learnt how to correct this, lets change the code a little bit.

This was the code without error handling.

use std::io;

fn main() {

    println!("Guess a number");

    let stdin = io::stdin();
    let mut guess: i32;
    let mut line = String::new();

    //get user input
    stdin.read_line(&mut line).unwrap();

    //Parse input string to integer
    //Not error handled
    guess = line.trim().parse().unwrap();

}

The parse() method returns a result object. The result object would have Ok() and Err() values. So if it is OK we can run a function with the parsed value passed to it. If it is an error we can handle it gracefully and say “Listen idiot, you have to enter a number. A NUMBAAA”.

For this we use the match function or statement or whatever it is called. It seem to act like the switch statement.

So here is the update code for the number guessing game.

use std::io;

fn main() {

    println!("Guess a number");

    let stdin = io::stdin();
    let mut guess: i32;
    let mut line = String::new();

    //get user input
    stdin.read_line(&mut line).unwrap();

    //Parse input string to integer
    //Error handled 
    guess = match line.trim().parse() {
        Ok(num) => num,
        Err(_) =>{
            println!("Please enter a number");
            return;
        }
    };
}

With the loop and game –

use std::io;
extern crate rand;
use rand::Rng;

fn main() {
    //Generate a random number
    let num = rand::thread_rng().gen_range(0, 10);

    println!("Guess a number");

    let stdin = io::stdin();
    let mut guess: i32;

    while ( true ){
        let mut line = String::new();

        //get user input
        stdin.read_line(&mut line).unwrap();

        //Parse input string to integer
        //Error is handled
        guess = match line.trim().parse() {
            Ok(num) => num,
            Err(_) =>{
                println!("Please enter a number");
                continue;
            }
        };

        //If the guess is correct exit the loop
        if( guess == num ){
            println!("Correct the number was {}", guess);
            break;
        }
        else{
            println!("Wrong. Not {}", guess);
        }
    }
}

There you go rust book, I beat you at your own game.

//Also instead of using

while( true ){
    //code
}

//You could just do this

loop{
    //code
}