Monday, 12 June 2017

Network Programming


  • Network applications are everywhere. 
  • Any time you browse the Web, send an email message, or pop up an X window, you are using a network application.
  • Python provides two levels of access to network services.
  •  At a low level, you can access the basic socket support in the underlying operating system,which allows you to implement clients and servers for both connection-oriented and connection-less protocols.
  • Python also has libraries that provide higher-level access to specific application-level network protocols, such as FTP, HTTP, and so on.
  • understanding on most famous concept in Networking - Socket Programming.
What is Socket ?
  • Sockets are the endpoints of a bidirectional communications channel. 
  • Sockets may communicate within a process, between processes on the same machine, or between processes on different continents.
  • Sockets may be implemented over a number of different channel types: Unix domain sockets, TCP, UDP, and so on. 
Client:


import socket               
# Import socket module

s = socket.socket( )         
# Create a socket object
host = socket.gethostname( ) 
# Get local machine name
port = 12345                
# Reserve a port for your service
s.connect((host, port))
print s.recv(1024)
s.close  

Client example2:

 import socket
clientsocket=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientsocket.connect(('localhost', 8089))
clientsocket.send('hello')

Client example3:

import socket
import sys

# Create a TCP/IP socket
sock=socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Connect the socket to the port where the server is listening
server_address = ('localhost', 9999)
print >>sys.stderr, 'connecting to %s port %s' % server_address
sock.connect(server_address)
try:
    
    # Send data
    message = 'This is the message.  It will be repeated.'
    print >>sys.stderr, 'sending "%s"' % message
    sock.sendall(message)

    # Look for the response
    amount_received = 0
    amount_expected = len(message)
    
    while amount_received < amount_expected:
        data = sock.recv(16)
        amount_received += len(data)
        print >>sys.stderr, 'received "%s"' % data

finally:
    print >>sys.stderr, 'closing socket'
    sock.close( )

Server :

import socket               
# Import socket module

s = socket.socket( )         
# Create a socket object
host = socket.gethostname( ) 
# Get local machine name
port = 12345                
# Reserve a port for your service.
s.bind((host, port))        
# Bind to the port

s.listen(5)                 
# Now wait for client connection.
while True:
   c, addr = s.accept()     
# Establish connection with client.
   print 'Got connection from', addr
   c.send('Thank you for connecting')
   c.close()                
# Close the connection

Server example2:

import socket

serversocket=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.bind(('localhost', 8089))
serversocket.listen(5) 
# become a server socket, maximum 5 connections

while True:
    connection, address = serversocket.accept()
    buf = connection.recv(64)
    if len(buf) > 0:
        print buf
        break

Server Example3:

import socket
import sys

# Create a TCP/IP socket
sock=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind the socket to the port
server_address = ('localhost', 9999)
print >>sys.stderr, 'starting up on %s port %s' % server_address
sock.bind(server_address)
# Listen for incoming connections
sock.listen(1)

while True:
    # Wait for a connection
    print >>sys.stderr, 'waiting for a connection'
    connection, client_address = sock.accept()
    try:
        print >>sys.stderr, 'connection from', client_address

        # Receive the data in small chunks and retransmit it
        while True:
            data = connection.recv(16)
            print >>sys.stderr, 'received "%s"' % data
            if data:
                print >>sys.stderr, 'sending data back to the client'
                connection.sendall(data)
            else:
                print >>sys.stderr, 'no more data from', client_address
                break
            
    finally:
        # Clean up the connection
        connection.close( )


Connecting to server:

example:

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

example:

import socket 
import sys 

try:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    print "Socket successfully created"
except socket.error as err:
    print "socket creation failed with error %s" %(err)

# default port for socket
port = 80

try:
    host_ip = socket.gethostbyname('www.google.com')
except socket.gaierror:
    # this means could not resolve the host
    print "there was an error resolving the host"
    sys.exit()

# connecting to the server
s.connect((host_ip,port))

print "the socket has successfully connected to google \
on port == %s" %(host_ip)

Server:

# 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()              

Client:

# 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
s.connect(('127.0.0.1', port))

# receive data from the server
print s.recv(1024)
# close the connection
s.close()                     
         

No comments:

Post a Comment