Socket programming in Python

Python, in default offers low-level access to network services as many other languages do. This is often required when developing client-server applications or an application which needs to communicate with another service. Therefore in this article, it is discussed, how socket programming can be achieved in Python.

Low-Level Access

In this approach, python library socket is used. It is a part of the standard Python library, hence no manual installation is required.

Server code

This is a simple server which keeps listening to an incoming traffic from a client and then respond.


import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

HOST = ''
PORT = 30303

s.bind((HOST, PORT))

while True:
   print ('server running --')
   conn, addr = s.accept()
   data = conn.recv(BUFFER_SIZE)
   print ('Got connection from ', data, '-', addr)
   conn.send(b'Thank you for connecting')

Note how the socket object has been initialized and then HOST address and the PORT have been defined. bind( ) method reserves the port for the host. accept( ) method accepts the incoming connection and then output another instance of the socket object as conn and the addr holds the address (and the port) of the incoming request.

When sending data using send( ) method, the content should be a byte-like object. No string objects can be used. That is why b literal is used. Or string.encode( ) can also be used here. The rest is pretty straight forward.

Client Code

Following is the code snippet for the client.
Code is almost as same as the server code other than not having a loop to listen to the incoming traffic. It simply send some data to the server and then receives the output from the server.


import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
HOST = ''
PORT = 30303

s.connect((HOST, PORT))
data = s.recv(1024)
print (data)
s.close ()

The server code needs to be executed first and then the client code.

However, since there is no threads in the server code, only 1 connection can be established with the server at a time.

Requesting a web page

It is possible to use the client code to contact a web server (or any other service) and request a web page. Or even contact a FTP service. The send request needs to be modified according to the protocol.

Following is a simple example on getting a web page using the client code. Localhost is used in the code however the HOST can be replaced with any URL which supports HTTP.


import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
HOST = ''
PORT = 80

s.connect((HOST, PORT))
s.send(b'GET /test/index.php HTTP/1.1\n'
       b'Connection: keep-alive\n'
       b'Upgrade-Insecure-Requests: 1\n'

data = s.recv(1024)
print (data)
s.close ()

Notice that only the send method has been changed to facilitate HTTP protocol. The output is a plain-text including header and body content. Further processing is required.

High-Level Access

For HTTP protocol, httplib module can be used too. However it is not a part of the standard Python library and it is required to get it installed manually. In the same manner, few non-standard libraries are available for FTP (ftplib), SMTP (smtplib), POP3 (poplib) protocols.

This is a simple introduction on socket programming in Python. According to your requirement the code needs to be modified. The intention was to demonstrate how Python can be used for the above mentioned purpose.


Flick – a new time unit for VR

Recently, the Facebook Open Source has announced that they have launched a new time unit called flick[1]. It captures the attention of many tech communities around the world. But why it is that cool? In this post, will discuss how it is derived using simple mathematical concepts.

The video sampling is measured by the frame rate, for general use it is frames fer second or for high speed motions capturing, frames per millisecond. That means number of frames displayed per time unit. 24 fps (frames per second) is one of the most common frame rate for films. That means 24 frames will be captured/ projected in a second, 24 images in a second.

Following video frame rates with 1/1000 subdivisions are considered when deriving this new unit, flick.

24 fps, 25 fps, 30 fps, 48 fps, 50 fps, 60 fps, 90 fps, 100 fps, 120 fps

when converted to numbers, considering 1/1000 sub divisons:

24 000, 25 000, 30 000, 48 000, 50 000, 60 000, 90 000, 100 000, 120 000

Then not only video, audio is also sampled. In the following manner.

8 kHz, 16 kHz, 22.05 kHz, 24 kHz, 32 kHz, 44.1 kHz, 48 kHz, 88.2 kHz, 96 kHz, 192 kHz

When converted into numbers.

8 000, 16 000, 22 050, 24 000, 32 000, 44 100, 48 000, 88 200, 96 000, 192 000

The new time unit is chosen in a such a way that the above rates can be represented with no fractions, the result is a full integer value. It can be noticed that it is inevitable getting fractions even a nano-second is used as the smallest time unit.

If the new value is f then following equation should be the new representation:

flick value representation = f / (video or audio sample rate)

To find out f, Least Common Multiple (LCM) should be calculated in following numbers.

24 000, 25 000, 30 000, 48 000, 50 000, 60 000, 90 000, 100 000, 120 000, 8 000, 16 000, 22 050, 24 000, 32 000, 44 100, 48 000, 88 200, 96 000, 192 000

However, it can be noticed at once, that the number list can be reduced before applying LCM. Because 48 is a multiple of 24, 90 is multiple of 30, therefore the list reduces as follow :(eliminate smaller number which is factor of a larger number)

90 000, 100 000, 120 000, 88 200, 192 000

then after, it is possible to prime factorize above numbers: (you may use the following calculator[3])

90 000 = 2 x 2 x 2 x 2 x 3 x 3 x 5 x 5 x 5 x 5 = 2^4 x 3^2 x 5^4
100 000 = 2 x 2 x 2 x 2 x 2 x 5 x 5 x 5 x 5 x 5 = 2^5 x (5^5)
120 000 = 2 x 2 x 2 x 3 x 5 = 2^3 x 3 x 5
88 200 = 2 x 2 x 2 x 3 x 3 x 5 x 5 x 7 x 7 = 2^3 x (3^2) x 5^2 x (7^2)
192 000 = 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 3 x 5 x 5 x 5 = (2^9) x 3 x 5^3

According to the method, the next step is to extract higher power primes.

= 2^9 x 3^2 x 5^5 x 7^2
= 512 x 9 x 3125 x 49
f = 705 600 000

If a flick is defined as one, 705 600 000th of a second, all above mentioned rates can be divided without getting any fractions as the result. The result is an integer always.

Further, a flick is nearly 1.4 times larger than a nano-second.

f = (1/ 705 600 000) second
f = 1.41723356 e-9 second

A video with a common rates such as 24 fps (video sampling rate) and 44.1 kHz (audio sampling rate) can now be expressed as 29 400 000 flicks (video rate) and 16 000 flicks (audio rate). Or even it can be denoted 29.4 mega-flicks and 16 kilo-flicks. (could not find any reference for using mega or kilo with flicks anyway)

That is how, the new unit, flick enables conversion of rates without any lose of information of the video sampling or the audio sampling. That is why it becomes a cool representation. C++ implementation can be found in GitHub[2]


Get Free Air Tickets [Hoax]

These days, getting free stuffs from businesses is not an uncommon thing, even from airlines. There are plenty of offers out there. One of my friends has forwarded the following message in WhatsApp.


Free 2 tickets, wow ! I could not wait till I finished reading the message. Because it is all about 2 free tickets from the national carrier. This is unbelievable. So I did check the URL, first it seems that the URL is as same as the official URL of the carrier which is Everything seems pretty cool. So I read it again and checked the URL. Then it flipped. The URL is srilanká , notice the letter á, instead of a.

If you visit the website, it looks as follow. It looks real, almost real, even the logo is also there.


You need to provide some answers, basically YES and NO for 4 questions and congratulations, you secured 2 free tickets. In the next screen, you need to send this to your WhatsApp contacts. Then after you can claim your 2 free tickets.


This URL wont work for desktop browsers, it keeps saying that the offer is not valid for the region while it gets directed to the following URL The reason is pretty simple because it targets the mobile users as it needs WhatsApp to spread the news.

This is not a very smart phishing attack though it is mediocre. The attacker has matched the URL, it is so hard to notice the difference. The web site looks real too. However the Facebook section is not working at all. The connection is not secured (https). This is why you need to check for https always, make it a habit.

Although the offer of 2 free tickets raises your eyebrows, at the same time, it rings a bell. Because it is hard to believe that an airline is just throwing 2 free tickets for a simple survey like this. It would feel real, if it was like 50% for tickets or somewhat.

Finally, to avoid such malicious hoax, make sure you check the URL before you click it. Then look for https, a secure connection. Think before you share anything, specially when you are asked to share something via facebook, WhatsApp, Viber and etc. Last not the least, make sure you use your common sense too.

EDIT : Having https doesnt prove the authenticity. But not having https should ring a bell. So dont get confused. Checking for https (SSL EV) would be  good test.

Did you get the same message? If so what did you do?

Intuition of zero

Zero is my favorite number after i. This number, zero is strange. The concept is mind blowing. Same as the infinity, thanks to God, the infinity is not a number but a concept. In contrast, zero is a number. So we need to deal with it everyday. That is why, zero becomes one of my favorite numbers. And it is possible to talk about zero for hours.

Lets check basic four operators; addition, subtraction, multiplication and division against this strange number, zero.

Addition and Subtraction

Lets assume that you are planning a treat for your friends. You buy 5 toffees. Earlier you had no toffees. But now you have 5 toffees. Mathematically it can be denoted as

= 0 + 5 = 5

You have 5 toffees but your friends dont like the flavor, so they didnt take any. That can be denoted as;

= 5 – 0 = 5


Taking back the same example, you have 5 friends and if you are planning to buy 2 toffees per friend, you need to buy 5 * 2 = 10 toffees. Then your mind changes, you are planning to buy a chocolate and a toffee per friend. Then you will need to buy 5 * 1 = 5 toffees only. But if you change your mind and decide that you buy 2 chocolates per friend, then you need to buy 5 * 0 = 0 toffees and 5 * 2 = 10 chocolates. This makes sense. As you have 10 chocolates, your friends get 10 / 5 = 2 chocolates. Further since you have no toffees your friends get 0 / 5 = 0 toffees.

Therefore it is safely concluded that, addition, multiplication of 0 wont change the value. Multiplication by zero makes any value 0. If any value is divided by zero then it is zero again.

So far the maths align with our intuition.

Multiplication as Addition

Multiplication is a special form of addition. For an example 3 * 5 means adding 5, three times. As multiplication is commutative 5 * 3 gives the same results but as a convention it can be taken as adding 3, five times.

5 * 3 = 5 + 5 + 5 = 15 or 3 * 5 = 3 + 3 + 3 + 3 + 3 = 15

Then 5 * 0 can be taken as adding 0, five times. 0 + 0 + 0 + 0 + 0 = 0, however according to the convention 0 * 5 becomes senseless. Adding 5 zero times, meaning nothing is being done.

Division as Subtraction

Division is also a special form of subtraction. It says how many subtractions should be performed to reach zero. For an example 6 / 2 can be denoted as 6 – 2 – 2 – 2 , so it needs 3 subtractions, hence 6 / 2 = 3

In the same manner, 0 / 5 = 0 because 0 has already reached to zero and no subtraction is required.

So far zero is behaving rationally. Now will see how wired zero can become under certain circumstances.

Division by Zero

It is a fact that you know, when a number is divided by a small number the result gets very large. When the number becomes smaller the result gets much more larger. 0 is the absolute smallest number. Therefore, if a number is divided by zero then it should become the infinity. This is quite intuitive though it is not correct.

Lets take an analogy. You have to distribute 10 chocolates among 5 friends. One friend takes 2 chocolates . Then 8 chocolates left for 4 friends. Still 8 / 4 = 2. Then two more friends takes. Now you have 4 chocolates and 2 more friends to take. Another one takes 2 chocolates now just one friend and 2 chocolates, once the final friend takes 2 remaining chocolates, you have no friends to come and no chocolates to distribute. So no one gets a chocolates, as there are no chocolates to distribute and at the same time there is no friends left to get any chocolates. Therefore, following make no sense at all, does it suggest the infinity or zero. It suggests neither of them.

(no friends) /  (no toffees)

Consider division as a series of subtraction, as we checked earlier. Example: take 5 / 0. How many times 5 should be subtracted by zero so that the final answer to reach 0. It can be noted that it will never reach to 0.

5 – 0 – 0 ………………………………………………. – 0 – 0 ≠ 0

That is one of the ways to demonstrate 0 / 0 non-existence, why any number is divided by zero is not infinity. Therefore in mathematics, division by zero is not determinable, considered as an invalid operation. That is why before dividing by any number we make the assumption that the number is not equal to zero. It reaches to the infinity, but it never gets there. Calculus should be used to deal with such situations, but it is not in the scope of this article.

Multiplication zero by zero

Intutively, zero times zero would equal to zero. Because when a number is multiplied by zero, the result becomes zero. But there is an issue.

Coming back to the toffee example, it is decided to buy chocolates instead of toffees. The treat needs 10 chocolates as there are 5 friends and one gets two chocolates.  But how many toffees to buy. All friends got chocolates therefore there is no friend to get toffees and at the same time you have not decided to give toffees, therefore it sounds like 0 * 0. Does it make sense, if so above example on 0 / 0 should make sense as well.

On the other hand, we noted that 5 * 0 = 0 + 0 + 0 + 0 + 0,

then, 4 * 0 = 0 + 0 + 0 + 0

and 3 * 0 = 0 + 0 + 0
2 * 0 = 0 + 0
1 * 0 = 0
but what is 0 * 0 = ?

Anyhow, if you can remember, this issue occurs on 0 * 5 as well but taking commutative property, 0 *5 considered as 5 * 0. Here it has no meaning as it becomes 0 * 0 again.

That is why both 0 * 0 and 0 / 0 are counter intuitive.

Is 0 * 0, indeterminate?

In an instance, 0 * 0 becomes indeterminate. Check the following proof.

take 3 numbers such that x * y = z

then assign x = 0;

as we already know that any number multiplied by zero is zero, when x = 0

0 * y = 0 ——————————(B)

y can be any number, then divide the equation by y.

0 = 0 / y ———————————-(A)

Now you will realize, equation A can only be true if y is not equal to 0, when y is equal to 0 equation A cannot be true. It is illegal, that means in equation B, solution y = 0 does not exist. That means, 0 * y = 0 true only if y ≠ 0 only.

When 0 * 0 Becomes 0

It is known fact that, x * x reaches to zero when x is reaching to zero. But it never gets value zero. But in most equations it is easy to take 0 * 0 as 0. Even in some instances x / 0 can be considered as the infinity. Even 0 / 0 is common in calculus, it is not taken as not defined in calculus. In fact it is the begging of calculus. The answer changes as the hat you are wearing, mathematician, engineer, physicists and etc…

Therefore where you use the expression it can get the related meaning. But based on basic mathematics, it can be seen that 0 * 0 cannot be defined. There is no much harm if it is taken as 0 * 0 = 0 as well. But it cannot be generalized. This affects indexes of 0 as well. 0^2 ≠ 0 and generally 0 ^ n ≠ 0 where n > 0. This should be discussed in another article.

How this is started ?

Recently, I found an interesting question on Quora. Two numbers are such that their sum is equal to their product. What are these two numbers?

Intuitively, it seems like 0,0 and 2,2 are the solutions but 0,0 is not (as 0 * 0 ≠ 0 + 0 but 2 * 2 = 2 + 2). That started the argument on what is 0 * 0 and this is my explanation on that.


I believe 0 * 0 is not 0. This is what I believe and the basis is explained above. This is open for discussions, please feel free to add your thoughts as well.

Higher denomination on notes vs Inflation

Money is one of my favorite subjects. The invention of currency and it’s valuation system feels so magical. In this article, will try to dig down the relevance of demonstrations to inflation.

Currencies such as Vietnamese dong (VND), Hungarian forint (HUF), Japanese yen (JPY), South Korean won (KRW), Cambodian riel (KHR) and ect. are having higher denominations. That means, there are lot of zeros in their bank notes. Have you ever wondered the reason?

In fact, the denomination is just a number, it has no real meaning if there is no information is available. For an example,  as at today, 1 South Korean Won (KRW) is equal to 0.00092 US dollars (USD). 50,000 KRW bank note is the highest denomination which is equal to 46 USD roughly. Vietnam has 500,000 VND bank note, which is the higher denomination on bank note among the region, I suppose. As at today, 1 VND is 0.000044 USD. The value of the highest note is nearly 30 USD.

Therefore actually the higher denomination alone doesnt mean much.

It is a known fact that the inflation plays a major role on deciding the denominations. Does it mean that those counties are associated to high inflation economies. Not really, as mentioned above, the denomination is just a number, if there is no information related to the currency is available. The reasons for having such high denominations can be due to many reasons. Inflation being one reason though. Without having information such as denominations over the past periods it is not possible to decide if the currency is currently facing any inflationary effects of the economy.

For example, Japanese yen having high denomination, not because the economy of Japan is experiencing an inflation right now, but because it experienced devaluation of currency in World War II period. Same goes with the Vietnamese dong, (VND) in early 1980.

Taking Vietnamese dong, the economy of Vietnam maintained inflation rate of 3.2% in 2016[1]. That is pretty good value. But after 1975, there was a soaring inflation which reached above 450% in 1986. So the high denomination could be due to the inflation occurred in 1980s. Without that information, the higher denomination of Vietnamese dong is just a number.

It is a fact that German economy collapsed in early 1900s, after the World War I due to inflation. It hit 29,500% of monthly inflation rate in 1923[3]. How come at present they have lower denominations then? The reason is, in 1923 the currency was German Papiermark. Later Rentenmark replaced Papiermark at the rate of 1 trillion Papiermark per 1 Rentenmark.

Another good example is Hungary. In July 1946, it hit 207.19%, daily inflation rate. Hungarian pengo was the currency at that time and it has been replaced by korona, and then later korona is replaced by forint (HUF) which is the official currency of Hungary today. The highest denomination of a bank note is 20,000 HUF even though the inflation rate is 0.4 % in 2016[2].

Zimbabwe faced the same issue recently. At this moment the official currency is the US dollar. Zimbabwean dollar was discontinued in 2009 as the inflation rate reached sky high. The highest denomination was 1.0e14. (14 zeros after 1)[3]. The daily inflation rate was 98%.

Another reason for having high denominations could be, not having decimal part in the currency. South Korean won or Japan yen have no decimals in the currency. Therefore when it is required to denote the smallest amount, higher denomination is required, even though it is not possible to buy anything using 1 KRW.

Apparently, it is not possible to compare currencies using the denomination. No currency gets stronger or weaker based on denomination of the notes, even though it feels that way. When taking alone, it is just a number and nothing else.


Higher denomination of a currency mean nothing much if no information of the currency presents. Inflation could be a reason for higher denominations.




Move the last digit and double the number

Check if you can solve the following:

The objective is to find a number which gets doubled when the last digit of the number is moved to the front of the number.

For an example:

Let abcd is the number, it should get doubled when d which is the last digit, is moved to the front, forming dabc 

2 x abcd = dabc

can you find such a number or few numbers?

First I started building the following equation:

Let x is positive integer and y is a single digit.

x > 0 and 10 > y > 0

therefore, the number can be written as;

2 . (10 . x + y ) = (y . 10^p) + x 


x = [ (10^p) – 2 ] * [y / 19]


y = [19 . x ] / [(10^p) – 2 ]

Then after, it is possible to solve this using trail and error method. It is cumbersome, yet possible. I was tying to figure out a heuristic method to get the answer, but I could not. Therefore I though of using a python script to get the answer.

def eqx(n, y):
    return int(((10**n)-(2))*(y/19))

def eqy(n, x):
    return int((19*x)/((10**n)-2))

def num_conv(num1, num2, p):
    d2 = num1%10
    d1 = int(num1/10)
    if(num2==((d2*10**p)+d1) and (10**p<num1)):
        return True
    return False

for i in range(0,300):
    for j in range(0,10):
        x = eqx(i,j)
        y = eqy(i,x)

        num1 = int((10*x)+y)
        num2 = int((y*(10**i))+x)

        LHS = 2*num1
        RHS = num2
        num_shuffled = num_conv(num1,num2,i)
        if ((LHS==RHS) and (num_shuffled) and (x!=0)):
            print (format(num1, ',d'),' shifting last digit ',format(num2, ',d'))
            print ('LHS',format(LHS, ',d'), ' RHS',format(RHS, ',d'))


x,y,p 10526315789473684 2 17
105,263,157,894,736,842 shifting last digit 210,526,315,789,473,684
LHS 210,526,315,789,473,684 RHS 210,526,315,789,473,684

x,y,p 15789473684210526 3 17
157,894,736,842,105,263 shifting last digit 315,789,473,684,210,526
LHS 315,789,473,684,210,526 RHS 315,789,473,684,210,526

x,y,p 21052631578947368 4 17
210,526,315,789,473,684 shifting last digit 421,052,631,578,947,368
LHS 421,052,631,578,947,368 RHS 421,052,631,578,947,368

x,y,p 31578947368421052 6 17
315,789,473,684,210,526 shifting last digit 631,578,947,368,421,052
LHS 631,578,947,368,421,052 RHS 631,578,947,368,421,052

x,y,p 42105263157894736 8 17
421,052,631,578,947,368 shifting last digit 842,105,263,157,894,736
LHS 842,105,263,157,894,736 RHS 842,105,263,157,894,736

Later I found out these kind of numbers are called Parasitic numbers, OEIS sequence of A146088[2][3]. If you are interested, refer to the following Wikipedia article[1] as the starting point.


This article is licensed under the Creative Commons Attribution-Share Alike 3.0 Unported (CC BY-SA 3.0) license. 

Solving 6 – 2 + 1 : Think Like Machines?

Recently I have shared the following in my Facebook and it became an interesting discussion. In my next post, I ll post why I have shared it. For the moment will try to solve this !


Simple, right. Can you guess, which is the right answer and the method to achieve the answer?

I say all three methods could beright and so do 3 and 5 answers. But how?

Indeed few posted 3 while some posted 5, the correct answer is 5 (considering pure mathematical approach). But what is the correct method. Both methods, two and three are correct. Not sure?

Even though this is a very simple expression, it seems like many were confused with BODMAS or PEMDAS and mathematics.

BODMAS is the UK standard while PEMDAS is the USA version of it. There are few other variations such as BIDMAS, etc.. Apart from the precedence discussed in mathematics, these rules were developed to make the machines (computers, calculators etc) life easier. In order to feed expressions to machines and get a consistent output. Since their inability to think, we direct the thinking pattern using rules.

Forget any method you have followed, BODMAS or PEMDAS whatever. Will get back to our basics.

6 – 2 + 1 

Then it is possible to write the expression as follow (without changing it’s original meaning);

6 + (1 x -2 ) + 1

Indeed above is equal to

6 + (-2) + 1

Can you identify A + B + C there? Then can you remember the Associative Property?

A + B + C = (A + B) + C = A + (B + C )

Accordingly, do you agree with following?

6 + (-2) + 1 =  6 + [ (-2) + 1 ] =  ( 6 + 1 ) + (-2)


6 – 2 + 1 = 6 + (-2) + 1 = 6 – 1 = 7 – 2 = 5

This is why it says + and – are having equal precedence and calculation should be performed left to right. But it is a simplified version, used to teach machines to solve these expressions. Do not get trapped, use the basics always.

Then, how come 3 would be a right answer. If it is mentioned according to BODMAS the answer is 3, then it is incorrect. But if you design a rule as follow A – B + C = A – (B + C) then according to the assumption the answer is 3. If you check my post, you would see I have not mentioned any assumption or method followed. Therefore it should be in pure mathematical form. So here the most suitable or the correct answer would be 5 and the methods are two and three.

This is why we should always follow the method used to solve a problem rather than focusing the answer alone.

Mathematics is a universal language, so why we need to stick to some rules developed to make the life of the machines easier.