You are on page 1of 23

Name- Ayan Sadhukhan

Regd Number- 19BCE1872


Faculty In-charge- Subbulakshmi P

Submission 4(Hamming Code)


Question:
Write the chat program to establish a connection between TCP server and TCP
client. Establish a connection between a server and client. Send a message from
client and display the same message in server and send back to the client. The
process should include the conversion of the message to the corresponding
hamming code in both the code. After receiving the message in hamming code
the message will be checked if there is any error in the message and will display
the message
Language Used - Python

Code 1(Server Code):


# server.py
import time, socket, sys

print("\nWelcome to Chat Room\n")


print("Initialising....\n")
time.sleep(1)

s = socket.socket()
host = socket.gethostname()
ip = socket.gethostbyname(host)
port = 1234
s.bind((host, port))
print(host, "(", ip, ")\n")
name = input(str("Enter your name: "))

s.listen(1)
print("\nWaiting for incoming connections...\n")
conn, addr = s.accept()
print("Received connection from ", addr[0], "(", addr[1], ")\n")

s_name = conn.recv(1024)
s_name = s_name.decode()
print(s_name, "has connected to the chat room\nEnter [e] to exit chat room\n")
conn.send(name.encode())

def BinaryToDecimal(binary):

# Using int function to convert to


# string
string = int(binary, 2)

return string

def calcRedundantBits(m):

# Use the formula 2 ^ r >= m + r + 1


# to calculate the no of redundant bits.
# Iterate over 0 .. m and return the value
# that satisfies the equation

for i in range(m):
if(2**i >= m + i + 1):
return i

def posRedundantBits(data, r):

# Redundancy bits are placed at the positions


# which correspond to the power of 2.
j=0
k=1
m = len(data)
res = ''

# If position is power of 2 then insert '0'


# Else append the data
for i in range(1, m + r+1):
if(i == 2**j):
res = res + '0'
j += 1
else:
res = res + data[-1 * k]
k += 1

# The result is reversed since positions are


# counted backwards. (m + r+1 ... 1)
return res[::-1]
def calcParityBits(arr, r):
n = len(arr)

# For finding rth parity bit, iterate over


# 0 to r - 1
for i in range(r):
val = 0
for j in range(1, n + 1):

# If position has 1 in ith significant


# position then Bitwise OR the array value
# to find parity bit value.
if(j & (2**i) == (2**i)):
val = val ^ int(arr[-1 * j])
# -1 * j is given since array is reversed

# String Concatenation
# (0 to n - 2^r) + parity bit + (n - 2^r + 1 to n)
arr = arr[:n-(2**i)] + str(val) + arr[n-(2**i)+1:]
return arr

def detectError(arr, nr):


n = len(arr)
res = 0

# Calculate parity bits again


for i in range(nr):
val = 0
for j in range(1, n + 1):
if(j & (2**i) == (2**i)):
val = val ^ int(arr[-1 * j])

# Create a binary no by appending


# parity bits together.

res = res + val*(10**i)

# Convert binary to decimal


return int(str(res), 2)

def detectAndCorrect(message):
data=list(message)
data.reverse()
c,ch,j,r,error,h,parity_list,h_copy=0,0,0,0,0,[],[],[]

for k in range(0,len(data)):
p=(2**c)
h.append(int(data[k]))
h_copy.append(data[k])
if(p==(k+1)):
c=c+1

for parity in range(0,(len(h))):


ph=(2**ch)
if(ph==(parity+1)):

startIndex=ph-1
i=startIndex
toXor=[]

while(i<len(h)):
block=h[i:i+ph]
toXor.extend(block)
i+=2*ph

for z in range(1,len(toXor)):
h[startIndex]=h[startIndex]^toXor[z]
parity_list.append(h[parity])
ch+=1
parity_list.reverse()
error=sum(int(parity_list) * (2 ** i) for i, parity_list in enumerate(parity_list[::-1]))

if((error)==0):
print('There is no error in the hamming code received')

str_data =' '

for i in range(0, len(message), 7):

temp_data = message[i:i + 7]

decimal_data = BinaryToDecimal(temp_data)

str_data = str_data + chr(decimal_data)


print(s_name, ":", str_data)

elif((error)>=len(h_copy)):
print('Error cannot be detected')

str_data =' '

for i in range(0, len(message), 7):

temp_data = message[i:i + 7]

decimal_data = BinaryToDecimal(temp_data)

str_data = str_data + chr(decimal_data)

print(s_name, ":", str_data)

else:
print('Error is in',error,'bit')

if(h_copy[error-1]=='0'):
h_copy[error-1]='1'
elif(h_copy[error-1]=='1'):
h_copy[error-1]='0'
print('After correction hamming code is:- ')
h_copy.reverse()
f=int(''.join(map(str, h_copy)))

str_data =' '

for i in range(0, len(f), 7):

temp_data = message[i:i + 7]

decimal_data = BinaryToDecimal(temp_data)

str_data = str_data + chr(decimal_data)

print(s_name, ":", str_data)

while True:
message = input(str("Me : "))
message2=message
data = ''.join(format(ord(i), 'b') for i in message)

m = len(data)
r = calcRedundantBits(m)

# Determine the positions of Redundant Bits


arr = posRedundantBits(data, r)

# Determine the parity bits


arr = calcParityBits(arr, r)

conn.send(arr.encode())
conn.send(message2.encode())
#conn.send(message.encode())
message = conn.recv(1024)
message2 = conn.recv(1024)
message=message.decode()
message2=message2.decode()

print(s_name, ":", message2)


print(message, "is the hamming code received ")
data=list(message)
data.reverse()
c,ch,j,r,error,h,parity_list,h_copy=0,0,0,0,0,[],[],[]
for k in range(0,len(data)):
p=(2**c)
h.append(int(data[k]))
h_copy.append(data[k])
if(p==(k+1)):
c=c+1

for parity in range(0,(len(h))):


ph=(2**ch)
if(ph==(parity+1)):

startIndex=ph-1
i=startIndex
toXor=[]

while(i<len(h)):
block=h[i:i+ph]
toXor.extend(block)
i+=2*ph

for z in range(1,len(toXor)):
h[startIndex]=h[startIndex]^toXor[z]
parity_list.append(h[parity])
ch+=1
parity_list.reverse()
error=sum(int(parity_list) * (2 ** i) for i, parity_list in enumerate(parity_list[::-1]))

if((error)==0):
print('There is no error in the hamming code received')

str_data =' '

for i in range(0, len(message), 7):

temp_data = message[i:i + 7]

decimal_data = BinaryToDecimal(temp_data)

str_data = str_data + chr(decimal_data)

print(s_name, ":", str_data)

elif((error)>=len(h_copy)):
print('Error cannot be detected')

str_data =' '

for i in range(0, len(message), 7):

temp_data = message[i:i + 7]

decimal_data = BinaryToDecimal(temp_data)
str_data = str_data + chr(decimal_data)

print(s_name, ":", str_data)

else:
print('Error is in',error,'bit')

if(h_copy[error-1]=='0'):
h_copy[error-1]='1'

elif(h_copy[error-1]=='1'):
h_copy[error-1]='0'
print('After correction hamming code is:- ')
h_copy.reverse()
f=int(''.join(map(str, h_copy)))

str_data =' '

for i in range(0, len(f), 7):

temp_data = message[i:i + 7]

decimal_data = BinaryToDecimal(temp_data)
str_data = str_data + chr(decimal_data)

print(s_name, ":", str_data)

#message = message.decode()
#print(s_name, ":", message)

Code 2(Client Code):


# client.py
import time, socket, sys

def BinaryToDecimal(binary):

# Using int function to convert to


# string
string = int(binary, 2)
return string

def calcRedundantBits(m):

# Use the formula 2 ^ r >= m + r + 1


# to calculate the no of redundant bits.
# Iterate over 0 .. m and return the value
# that satisfies the equation

for i in range(m):
if(2**i >= m + i + 1):
return i

def posRedundantBits(data, r):

# Redundancy bits are placed at the positions


# which correspond to the power of 2.
j=0
k=1
m = len(data)
res = ''

# If position is power of 2 then insert '0'


# Else append the data
for i in range(1, m + r+1):
if(i == 2**j):
res = res + '0'
j += 1
else:
res = res + data[-1 * k]
k += 1

# The result is reversed since positions are


# counted backwards. (m + r+1 ... 1)
return res[::-1]

def calcParityBits(arr, r):


n = len(arr)

# For finding rth parity bit, iterate over


# 0 to r - 1
for i in range(r):
val = 0
for j in range(1, n + 1):

# If position has 1 in ith significant


# position then Bitwise OR the array value
# to find parity bit value.
if(j & (2**i) == (2**i)):
val = val ^ int(arr[-1 * j])
# -1 * j is given since array is reversed

# String Concatenation
# (0 to n - 2^r) + parity bit + (n - 2^r + 1 to n)
arr = arr[:n-(2**i)] + str(val) + arr[n-(2**i)+1:]
return arr
def detectError(arr, nr):
n = len(arr)
res = 0

# Calculate parity bits again


for i in range(nr):
val = 0
for j in range(1, n + 1):
if(j & (2**i) == (2**i)):
val = val ^ int(arr[-1 * j])

# Create a binary no by appending


# parity bits together.

res = res + val*(10**i)

# Convert binary to decimal


return int(str(res), 2)

def detectAndCorrect(message):
data=list(message)
data.reverse()
c,ch,j,r,error,h,parity_list,h_copy=0,0,0,0,0,[],[],[]

for k in range(0,len(data)):
p=(2**c)
h.append(int(data[k]))
h_copy.append(data[k])
if(p==(k+1)):
c=c+1

for parity in range(0,(len(h))):


ph=(2**ch)
if(ph==(parity+1)):

startIndex=ph-1
i=startIndex
toXor=[]

while(i<len(h)):
block=h[i:i+ph]
toXor.extend(block)
i+=2*ph

for z in range(1,len(toXor)):
h[startIndex]=h[startIndex]^toXor[z]
parity_list.append(h[parity])
ch+=1
parity_list.reverse()
error=sum(int(parity_list) * (2 ** i) for i, parity_list in enumerate(parity_list[::-1]))

if((error)==0):
print('There is no error in the hamming code received')

str_data =' '

for i in range(0, len(message), 7):


temp_data = message[i:i + 7]

decimal_data = BinaryToDecimal(temp_data)

str_data = str_data + chr(decimal_data)

print(s_name, ":", str_data)

elif((error)>=len(h_copy)):
print('Error cannot be detected')

str_data =' '

for i in range(0, len(message), 7):

temp_data = message[i:i + 7]

decimal_data = BinaryToDecimal(temp_data)

str_data = str_data + chr(decimal_data)


print(s_name, ":", str_data)

else:
print('Error is in',error,'bit')

if(h_copy[error-1]=='0'):
h_copy[error-1]='1'

elif(h_copy[error-1]=='1'):
h_copy[error-1]='0'
print('After correction hamming code is:- ')
h_copy.reverse()
f=int(''.join(map(str, h_copy)))

str_data =' '

for i in range(0, len(f), 7):

temp_data = message[i:i + 7]

decimal_data = BinaryToDecimal(temp_data)

str_data = str_data + chr(decimal_data)

print(s_name, ":", str_data)


print("\nWelcome to Chat Room\n")
print("Initialising....\n")
time.sleep(1)

s = socket.socket()
shost = socket.gethostname()
ip = socket.gethostbyname(shost)
print(shost, "(", ip, ")\n")
host = input(str("Enter server address: "))
name = input(str("\nEnter your name: "))
port = 1234
print("\nTrying to connect to ", host, "(", port, ")\n")
time.sleep(1)
s.connect((host, port))
print("Connected...\n")

s.send(name.encode())
s_name = s.recv(1024)
s_name = s_name.decode()
print(s_name, "has joined the chat room\nEnter [e] to exit chat room\n")

while True:
message = s.recv(1024)
message2=s.recv(1024)
message2=message2.decode()
message = message.decode()

print(s_name,":",message2)
print(message," is the hamming code message received")
detectAndCorrect(message)

message = input(str("Me : "))


message2= message
data = ''.join(format(ord(i), 'b') for i in message)

m = len(data)
r = calcRedundantBits(m)

# Determine the positions of Redundant Bits


arr = posRedundantBits(data, r)

# Determine the parity bits


arr = calcParityBits(arr, r)

if message2 == "[e]":
message2 = "Left chat room!"
s.send(message2.encode())
#s.send(arr)
print("\n")
break
s.send(arr.encode())

s.send(message2.encode())
Output 1(Client side) :

Output 2(Server side):

You might also like