Saturday, 24 May 2025

chat bot using python

 #chatbot

import nltk

import re


def chatbot():

    while True:

        user_input = input("User: ")

        user_input = user_input.lower()

        user_input = re.sub(r'[^\w\s]', '', user_input)

        tokens = nltk.word_tokenize(user_input)


        if 'hello' in tokens:

            print("Chatbot: Hi there!")

        elif 'bye' in tokens:

            print("Chatbot: Goodbye!")

            break

        else:

            print("Chatbot: Sorry, I didn't understand.")


chatbot()

Friday, 17 January 2025

Git Hub

 step1 : install git

step2 : install vscode

step3: login github

step4: open commandprompt  and type git

step5:

    git config --global user.name "jahabm"

    git config --global user.email "likejahab@gmail.com"

       (visual studio)

step 6 : open folder anyplace

step 7: open visual studio code and open the above folder

step 8 : open terminal (in visual studio)

           git clone https://github.com/Jahabm/test.git

step 9 : (open folder)

       PS C:\Users\G-TEC\Desktop\gtec> cd test

       PS C:\Users\G-TEC\Desktop\gtec\test>

step10 : create a new file(test2.txt)

step11 : open terminal (in visual studio)

                git status         (u)

                git add test2.txt 

                git status          (a)

                git commit -m "test2.txt added" 

                git push origin main

step12: git pull


Friday, 9 August 2024

Python - Multithreading

 ----------------------------------------------

Python Multithreading

----------------------------------------------

Multitasking:

---------------

-computer execute more than one program or task simultaneously or concurrently.


Types of Multitasking:

--------------------------

1. Process based Multitasking

2. Thread based Multitasking


1. Process based Multitasking:

-------------------------------------- 

-Each task is a separate independent process

Example for OS Level:

--------------------------

a) Typing a Python Program in the editor

b) Listening audio songs from the same system

c) Downloading new songs from the internet


2. Thread based Multitasking:

-------------------------------------- 

-Each task is an independent part of the same program

Ex:

 a) car games

 b) Access Internet

 c) User work with word(Typing,check grammar and print)

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

thread  :

-------- 

-A thread is a sequence of such instructions within a program that can be

 executed independently of other code.

-A thread is simply a subset of a process


Multithreading

------------------

-Multithreading is defined as the ability of a processor to execute 

  multiple threads concurrently.

-Multithreading is the ability of a program or an operating system process

 to manage its use by more than one user at a time and to even manage 

 multiple requests by the same user without having to have 

 multiple copies of the programming running in the computer.

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Thread Methods:

--------------------

1. start():start the thread activity

2. run()  :thread activity

3. join() :wait until the thread terminates

4. getName() : get thread Name

5. setName() : set thread Name

6. isAlive() : checks whether a thread is still executing

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

# creating thread in 3 ways

1) Creating a Thread without using any class

2) Creating a Thread by extending Thread class

3) Creating a Thread without extending Thread class

   ----------------------------------------------------

1) Creating a Thread without using any class

  -----------------------------------------------------

 #Program 1: Creating a Thread without using any class

 #Method 1

from threading import *

def display():

    for i in range(1,5):

        print(i," Thread")

#creation of thread object to execute display

t1=Thread(target=display)

t1.start()

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 2: Creating a Thread without using any class

 #Method 2

import threading

def display():

    for i in range(1,5):

        print(i," Thread")

#creation of thread object to execute display

t1=threading.Thread(target=display)

t1.start()

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

     ------------------------------------------------------

2) Creating a Thread by extending Thread class

   -------------------------------------------------------

#Program 1 : Creating a Thread by extending Thread class

 #Method 1

from threading import *

class MyThread(Thread):

    def run(self):

        for i in range(1,5):

            print(i," Thread")

#creation of thread object to execute display

t1=MyThread()

t1.start()

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 2 : Creating a Thread by extending Thread class

 #Method 2

import threading

class MyThread(threading.Thread):

    def run(self):

        for i in range(1,5):

            print(i," Thread")

#creation of thread object to execute display

t1=MyThread()

t1.start()

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

     -----------------------------------------------------------

3) Creating a Thread without extending Thread class

   -------------------------------------------------------------

#Program 1 : Creating a Thread without extending Thread class

#Method 1:

from threading import *

class one:

    def display(self):

        for i in range(1,5):

            print(i," Thread")

#creation of class object

obj=one()

t1=Thread(target=obj.display)

t1.start()

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 2 : Creating a Thread without extending Thread class

#Method 2:

import threading

class one:

    def display(self):

        for i in range(1,5):

            print(i," Thread")

#creation of class object

obj=one()

t1=threading.Thread(target=obj.display)

t1.start()

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

------------------------------

Using Thread Methods

-----------------------------

#Program 1: using Thread Methods

from threading import *

def display():

    print("welcome")

#creation of thread object to execute display

t1=Thread(target=display)

t1.start()

print("Current Thread :",current_thread())

print("Current Thread Name:",current_thread().name)

print("Thread Name :",t1.getName())

t1.setName("jahab")

print("Thread Name ",t1.getName())

print("Identification No :",t1.ident)

print("Alive or Not :",t1.isAlive())

print("Count :",active_count())

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 2: Example Program for Multithreading(single thread)

#Method 1:

from threading import *

import time

def msg1():

    time.sleep(0.5)

    print("Welcome")

    print("Current Thread ",current_thread().getName())

try:

    t1 = Thread(target=msg1)

# starting thread 1 

    t1.start() 

except:

   print ("Error: unable to start thread") 

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 3: Example Program for Multithreading(single thread)

#Method 2:

import threading

import time

def msg1(tname,delay):

    time.sleep(delay)

    print("Welcome to ",tname)

try:

    t1 = threading.Thread(target=msg1, args=("Thread-1",5)) 

 # starting thread 1 

    t1.start() 

except:

   print ("Error: unable to start thread") 

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 4: Example Program for Multithreading

import threading

import time

def msg1(tname,delay):

    time.sleep(delay)

    print("Welcome to ",tname)

def msg2(tname,delay):

    time.sleep(delay)

    print("Welcome to ",tname)

try:

    t1 = threading.Thread(target=msg1, args=("Thread-1",5))

    t2 = threading.Thread(target=msg2, args=("Thread-2",3)) 

 # starting thread 1 

    t1.start()

    print(threading.current_thread())

    print(t1.getName())

    t1.setName("jahab")

    print(t1.isAlive())

 # starting thread 2

    t2.start()

except:

   print ("Error: unable to start thread")

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 5: Example Program for Multithreading

import threading

import time

def msg1(tname,delay):

    for i in range(1,6):

        time.sleep(delay)

        print("Welcome to ",tname)

def msg2(tname,delay):

    for i in range(1,6):

        time.sleep(delay)

        print("Welcome to ",tname)

try:

    t1 = threading.Thread(target=msg1, args=("Thread-1",5))

    t2 = threading.Thread(target=msg2, args=("Thread-2",3)) 

 # starting thread 1 

    t1.start()

 # starting thread 2

    t2.start()     

except:

   print ("Error: unable to start thread") 

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 6: Example Program for Multithreading using join method

import threading

import time

def msg1(tname,delay):

    for i in range(1,5):

        time.sleep(delay)

        print("Welcome to ",tname)

def msg2(tname,delay):

    for i in range(1,5):

        time.sleep(delay)

        print("Welcome to ",tname)

try:

    t1 = threading.Thread(target=msg1, args=("Thread-1",5))

    t2 = threading.Thread(target=msg2, args=("Thread-2",3)) 

 # starting thread 1 

    t1.start()

 # wait until thread 1 is completely executed 

    t1.join()   

 # starting thread 2

    t2.start()     

 # wait until thread 2 is completely executed 

    t2.join() 


 # both threads completely executed 

    print("Done!") 

except:

   print ("Error: unable to start thread") 

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

------------------------------------

Daemon Thread

-------------------------------------

-The Main purpose is to provide support for non-daemon threads(main thread)

Ex: Garbage Collector

Note:

------

  -Once thread started we cannot change its Daemon nature

  -Default thread Nature : Non-Daemon

  -Whenever last Non-Daemon thread terminates automatically all Daemon threads will be 

   terminated, we are not required to terminate explicitly

  -supporting jobs can be implemented by Daemon threads

  -Main Jobs can be implemented by Non Daemon threads

  -The entire Python program exits when only daemon threads are left.

Ex:

1)car game

   cars--->Non Daemon

   background Sceneries--->Daemon 

2) Cinema Shooting

    Hero,Heroines--->Non-Daemon

    Maku up -->Daemon


Methods:

---------

1) isDaemon()

2) setDaemon(True)

3) setDaemon(False)

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 1 : Example for Daemon Thread

from threading import *

import time

def job1():

    for i in range(10):

        print("Job1")

        time.sleep(2)


t1=Thread(target=job1)

print(t1.isDaemon())

t1.setDaemon(True)

print(t1.isDaemon())

t1.start()

time.sleep(10)

print("End of Main Thread")

------------------------------------------------

#Program 2 : Example for Daemon Thread

import threading

import time

def print_work_a():

    print('Starting of thread :', threading.currentThread().name)

    #time.sleep(2)

    print('Finishing of thread :', threading.currentThread().name)



def print_work_b():

    print('Starting of thread :', threading.currentThread().name)

    print('Finishing of thread :', threading.currentThread().name)


a = threading.Thread(target=print_work_a, name='Thread-a', daemon=True)

#a = threading.Thread(target=print_work_a, name='Thread-a')

b = threading.Thread(target=print_work_b, name='Thread-b')


a.start()

b.start()

Python - JSON

 ------------------------------------------------------------------

Python JSON(JavaScript Object Notation Serializer)

----------------------------------------------------------------

Purpose: 

----------

-Encode Python objects as JSON strings, and decode JSON strings into Python objects.

-JSON is a syntax for storing and exchanging data.

-JSON is text, written with JavaScript object notation.

Uses:

------

-JSON (JavaScript Object Notation) is a lightweight data-interchange format

-The JSON format is often used for serializing and transmitting structured data over a network connection.

-It is used primarily to transmit data between a server and web application(client), serving as an alternative to XML.

-It is easy for humans to read and write. 

-It is easy for machines to parse and generate. 

-It is based on a subset of the JavaScript Programming Language, Standard ECMA

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

You can convert Python objects of the following types, into JSON strings:

dict, list, tuple, string, int, float, True, False, None

Difference between XML and JSON:

--------------------------------------------

-Both JSON and XML can be used to receive data from a web server.

-JSON is a Data Oriented , XML is a Document Oriented

-JSON Support arrays, XML Not support array

-JSON less secured, XML more Secured


JSON Example:

------------------

{"employees":[

    { "firstName":"Jahab", "lastName":"Deen" },

    { "firstName":"Anna", "lastName":"Smith" },

    { "firstName":"Peter", "lastName":"Jones" }

]}

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

XML Example:

------------------

<employees>

    <employee>

        <firstName>Jahab</firstName> <lastName>Deen</lastName>

    </employee>

    <employee>

        <firstName>Anna</firstName> <lastName>Smith</lastName>

    </employee>

    <employee>

        <firstName>Peter</firstName> <lastName>Jones</lastName>

    </employee>

</employees>   

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 1: Convert from JSON to Python

import json

# some JSON:

x =  '{ "name":"Jahab", "age":30, "city":"Trichy"}'

# parse x:

y = json.loads(x)

# the result is a Python dictionary:

print(y["name"])

print(y["age"])

print(y["city"])

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 2: Convert from Python to JSON

import json

# a Python object (dict):

x = {

  "name": "Jahab",

  "age": 30,

  "city": "Trichy"

}

# convert into JSON:

y = json.dumps(x)

# the result is a JSON string:

print(y)

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Note:

------

1) json.dumps(x, indent=4)   - Format the result

2) json.dumps(x, indent=4, separators=(". ", " = ")) - Separators

3) json.dumps(x, indent=4, sort_keys=True)   - Order the result

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 3: Convert from Python to JSON

import json

print(json.dumps({"name": "Jahab", "age": 30}))

print(json.dumps(["apple", "bananas"]))

print(json.dumps(("apple", "bananas")))

print(json.dumps("hello"))

print(json.dumps(42))

print(json.dumps(31.76))

print(json.dumps(True))

print(json.dumps(False))

print(json.dumps(None))

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Python - Iterator

Python Iterator

---------------------

An iterator is an object that contains a countable number of values.

An iterator is an object that can be iterated upon, meaning that you can traverse through all the values.

Iterator Methods:

---------------------

1. iter()  - used to get an iterator

2. next()- next() function to manually iterate through all the items of an iterator

~~~~~~~~~~~~~~~~~~~~~~~~

#Program 1 : Example program for iterator

a=[10,20,5,7,90]

i=iter(a)

print(next(i))

print(next(i))

print(i.__next__())

print(i.__next__())

print(i.__next__())

print(next(i))

~~~~~~~~~~~~~~~~~~~~~~~~

#Program 2 : Example program for iterator

mytuple = ("apple", "banana", "cherry")

myit = iter(mytuple)

print(next(myit))

print(next(myit))

print(next(myit))

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 3 : Example program for iterator

mystr = "jahab"

myit = iter(mystr)

print(next(myit))

print(next(myit))

print(next(myit))

print(next(myit))

print(next(myit))

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Python - Events

 Python events:

-----------------

 -The program enters mainloop()  which wait for events (user actions).

 -We define the button which has a callback to the function callback().

 -master is the root window, the window where your button will appear in.

- Events can be key presses or mouse operations by the user.

Note:

----------------------

I) Mouse Events:

   ----------------------

A). Button Events:

      ------------------

1) <Button-1> = left mouse button

2) <Button-2> = middle button

3) <Button-3> = The rightmost mouse button

4) <Button-4> = defines the scroll up event on mice with wheel support

5) <Button-5>  = the scroll down. 

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

B). Motion Events:

      ------------------

1) <B1-Motion> = Left

2) <B2-Motion> = Middle

3) <B3-Motion> = Right

~~~~~~~~~~~~~~~~~~~~~~~~~~~

C). ButtonRelease Events:

      --------------------------

1) <ButtonRelease-1> = Left Button is released

2) <ButtonRelease-2> = Middle Button is released

3) <ButtonRelease-3> = Right Button is released

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

D). DoubleButton Events:

      --------------------------

1) <Double-Button-1> = Left

2) <Double-Button-2> = Middle

3) <Double-Button-3>  = Right

~~~~~~~~~~~~~~~~~~~~~~~~~~~~

E). Mouse Entered & Leave Events:

     ----------------------------

1) <Enter> = Mouse Enter to widgets

2) <Leave> = Mouse Leave from widgets

-----------------------------------------------------------------------------

II) Keyboard Events:

   ----------------------

1) <FocusIn> - Focus to widget 

2) <FocusOut> - Focus from widget

3) <Return> - User Press Enter Key

4) <Key> - User Pressed any Key

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 1 : tkbutton with onclick event

from tkinter import *

master = Tk()

 

def msg():

    print ("click!")

b = Button(master, text="OK", command=msg)

b.pack()

mainloop()

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 2 : tkbutton with bind method

from tkinter import *

master = Tk()

 

def msg(event):

    print ("click!")


b = Button(master, text="OK")

master.bind('<Button-1>',msg)

b.pack()

mainloop()

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 3 : tkbutton with onclick event

from tkinter import *

master = Tk()

master.minsize(300,100)

master.geometry("320x100")

 

def callback():

    print ("click!")


photo=PhotoImage(file="1.gif")

b = Button(master,image=photo, command=callback, height=50, width=150)

b.pack()

mainloop()

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 4 : tkbutton with onclick event

from tkinter import *

master=Tk()

master.minsize(300,120)

master.geometry("320x120")


def add():

    a=int(a1.get())

    b=int(a2.get())

    c=a+b

    a3.set(c)#print c

def sub():

    a=int(a1.get())

    b=int(a2.get())

    c=a-b

    a3.set(c)#print c

    

def clear():

    a1.set("")

    a2.set("")

    a3.set("")

    

a1=StringVar()   #a1=IntVar()

a2=StringVar()   #a2=IntVar()

a3=StringVar()   #a3=IntVar()


t1=Entry(master,textvariable=a1)

t1.focus_set()

t1.pack()

t2=Entry(master,textvariable=a2)

t2.pack()

b1=Button(master,text="Add",command=add,width=20)

b1.pack()

b2=Button(master,text="Sub",command=sub,width=20)

b2.pack()

b3=Button(master,text="Clear",command=clear,width=20)

b3.pack()


t3=Entry(master,textvariable=a3)

t3.pack()

master.mainloop()

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 5 : tkbutton with bind method

from tkinter import *

master=Tk()

master.minsize(300,120)

master.geometry("320x220")


def add(event):

    a=int(a1.get())

    b=int(a2.get())

    c=a+b

    a3.set(c)#print c

def sub(event):

    a=int(a1.get())

    b=int(a2.get())

    c=a-b

    a3.set(c)#print c

    

def clear(event):

    a1.set("")

    a2.set("")

    a3.set("")

    

a1=StringVar()   #a1=IntVar()

a2=StringVar()   #a2=IntVar()

a3=StringVar()   #a3=IntVar()


t1=Entry(master,textvariable=a1)

t1.focus_set()

t1.pack()

t2=Entry(master,textvariable=a2)

t2.pack()

b1=Button(master,text="Add",width=20)

b1.bind('<Button-1>',add)

b1.pack()


b2=Button(master,text="Sub",width=20)

b2.bind('<Button-1>',sub)

b2.pack()


b3=Button(master,text="Clear",width=20)

b3.bind('<Button-1>',clear)

b3.pack()



t3=Entry(master,textvariable=a3)

t3.pack()

master.mainloop()

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 6: Button single click & double click

from tkinter import *

import sys


master=Tk()

def hello(event):

    print("Single Click, Button-l") 

def quit(event):                           

    print("Double Click, so let's stop")

    sys.exit()

    master.withdraw()


widget = Button(master, text='Mouse Clicks')

widget.pack()

widget.bind('<Button-1>', hello)

widget.bind('<Double-1>', quit) 

master.mainloop()

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 7:  Mouse events

from tkinter import *


class MouseLocation( Frame ):

   def __init__( self ):

      Frame.__init__( self )

      self.pack( expand = YES, fill = BOTH )

      self.master.title( "Demonstrating Mouse Events" )

      self.master.geometry(  "275x100" )

      

      self.mousePosition = StringVar() # displays mouse position

      self.mousePosition.set( "Mouse outside window" )

      self.positionLabel = Label( self,textvariable = self.mousePosition )

      self.positionLabel.pack( side = BOTTOM )


      self.bind( "<Button-1>", self.buttonPressed )

      self.bind( "<ButtonRelease-1>", self.buttonReleased )   

      self.bind( "<Enter>", self.enteredWindow )

      self.bind( "<Leave>", self.exitedWindow )

      self.bind( "<B1-Motion>", self.mouseDragged )


   def buttonPressed( self, event ):

      self.mousePosition.set( "Pressed at [ " + str( event.x ) + ", " + str( event.y ) + " ]" )


   def buttonReleased( self, event ):

      self.mousePosition.set( "Released at [ " + str( event.x ) + ", " + str( event.y ) + " ]" )


   def enteredWindow( self, event ):

      self.mousePosition.set( "Mouse in window" )


   def exitedWindow( self, event ):

      self.mousePosition.set( "Mouse outside window" )


   def mouseDragged( self, event ):

      self.mousePosition.set( "Dragged at [ " + str( event.x ) + ", " + str( event.y ) + " ]" )


MouseLocation().mainloop()

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Python - Networking

 ---------------------------

Python Networking:

---------------------------

-Sharing data between a Connected network(Wired/Wireless)


Python Network Services:

---------------------------------

There are two levels of network service access in Python. These are:

1. Low-Level Access(connect same system(client and server) via socket)

2. High-Level Access(Application level network protocols(HTTP, FTP.,,)


Socket:

--------

-A socket is the end-point in a flow of communication between two programs or communication channels operating over a network. 

Syntax:

--------

      g = socket.socket (socket_family, type_of_socket, protocol=value)


Some of the important server socket methods are:

------------------------------------------------------------

1) listen(): is used to establish and start TCP listener.

2) bind(): is used to bind address (host-name, port number) to the socket.

3) accept(): is used to TCP client connection until the connection arrives.

4) connect(): is used to initiate TCP server connection.

5) send(): is used to send TCP messages.

6) recv(): is used to receive TCP messages.

7) sendto(): is used to send UDP messages

8) close(): is used to close a socket.

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Step by step Socket programming

---------------------------------------

Step1 : importing the socket library

        Ex:

            import socket

Step 2 : making a simple socket(Socket creation)

        Ex: 

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

        Here,

          1) AF_INET - address family ipv4(internet protocol version 4)

          2) SOCK_STREAM - Connection oriented TCP Protocol

Step 3: Connecting to a server (find the ip of the server)

        Ex:

             import socket 

             ip = socket.gethostbyname('www.google.com')

             print(ip)

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 1: find the ip of the server using Python

import socket

try:

    ip1 = socket.gethostbyname('www.google.com')

    ip2 = socket.gethostbyname('www.gmail.com')

    ip3 = socket.gethostbyname('www.facebook.com')

    print(ip1)

    print(ip2)

    print(ip3)

except Exception as e1:

    print(e1)

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 2: find the Machine host name using Python

import socket

try:

    ip1 = socket.gethostbyname(socket.gethostname())

    print(ip1)

except Exception as e1:

    print(e1)

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 3 : An example script to connect to Google using socket programming in Python 

import socket # for socket 

import sys  

try: 

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

    print ("Socket successfully created")

except Exception as err: 

    print ("socket creation failed with error : ",err) 


# default port for socket 

port = 80

try: 

    host_ip = socket.gethostbyname('www.google.com') 

except Exception as err1: 

    print ("there was an error resolving the host",err1)

    sys.exit() 

# connecting to the server 

s.connect((host_ip, port)) 

print ("the socket has successfully connected to google on port =",host_ip) 

Output:

---------

Socket successfully created

the socket has successfully connected to google on port == 216.58.200.132

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 4 : Client and server Program

Step1: (save client1.py)

-----

# Import socket module 

import socket                

  

# Create a socket object 

s = socket.socket()          

  

# Define the port on which you want to connect 

port = 12345                

  

# connect to the server on local computer

ip1 = socket.gethostbyname(socket.gethostname())

s.connect((ip1, port)) 

  

# receive data from the server 

print(s.recv(1024)) 

# close the connection 

s.close()        

----------------------------

Step2: (server1.py)

# first of all import the socket library 

import socket                

  

# next create a socket object 

s = socket.socket()          

print ("Socket successfully created")

  

# reserve a port on your computer in our 

# case it is 12345 but it can be anything 

port = 12345                

  

# Next bind to the port 

# we have not typed any ip in the ip field 

# instead we have inputted an empty string 

# this makes the server listen to requests  

# coming from other computers on the network 

s.bind(('', port))         

print ("socket binded to %s" %(port)) 

  

# put the socket into listening mode 

s.listen(5)      

print ("socket is listening")

  

# a forever loop until we interrupt it or  

# an error occurs 

while True: 

  

   # Establish connection with client. 

   c, addr = s.accept()      

   print ('Got connection from', addr) 

  

   # send a thank you message to the client.  

   c.send('Thank you for connecting') 

  

   # Close the connection with the client 

   c.close() 

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~