Login Register






Thread Rating:
  • 0 Vote(s) - 0 Average


Python netwoking filter_list
Author
Message
Python netwoking #1
[shadow=black]PYTHON NETWORKING TUTORIAL[/shadow]

[shadow=green]Imports Needed:[/shadow]

socket


[shadow=red]Objects Used:[/shadow]
  • domain - he family of protocols that will be used as the transport mechanism
  • type - The type of communications between the two endpoints
  • protocol - be used to identify a variant of a protocol within a domain and type.
  • host - The identifier of a network interface
  • port - the port number to connect to the server




[shadow=blue]Examples/explenations of networking:[/shadow]


Code:
s = socket.socket (socket_family, socket_type, protocol=0)

To network in python we need to make initialize a socket variable, the above code does this and uses 3 separate variables to set up the socket. These variables are:
  • socket_family - either AF_UNIX or AF_INET (inet uses tcp/ip while unix creates a filesystem object)
  • socket_type - either SOCK_STREAM (for connection-oriented protocols) or SOCK_DGRAM (for connectionless protocols)
  • protocol - left out, default at 0


Sockets have methods for both the client and the server side of a program.

Server commands:

bind() - binds to an address
listen() - sets up and starts a TCP listener
accept() - allows clients to connect through TCP connections

Client commands:

connect() - connects to a server through a tcp connections

General commands:

recv() - receives TCP message
send() - sends TCP message
recvfrom() - receives UDP message
sendto() - sends UDP message
close() - closes socket
gethostname() - returns the hostname


an example of a server:

Code:
#!/usr/bin/python           # This is server.py file

import socket               # Import socket module

s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = 2223                 # 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


an example of a client:


Code:
#!/usr/bin/python           # This is client.py file

import socket               # Import socket module

s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = 2223               # Reserve a port for your service.

s.connect((host, port))
print s.recv(1024)
s.close                     # Close the socket when done




[shadow=black]I HOPE THIS TUTORIAL HELPED YOU! KEEP AN EYE OUT FOR MY OTHER NETWORKING TUTORIALS FOR DIFFERENT LANGUAGES![/shadow]
(This post was last modified: 02-01-2013, 06:06 AM by Frankie.)

Reply







Users browsing this thread: 1 Guest(s)