Socket programming using python [UDP]

What is Sockets?
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. The socket library provides specific classes for handling the common transports as well as a generic interface for handling the rest.
Sockets have their own vocabulary −
Sr.No. Term & Description
1 Domain
The family of protocols that is used as the transport mechanism. These values are constants such as AF_INET, PF_INET, PF_UNIX, PF_X25, and so on.
2 type
The type of communications between the two endpoints, typically SOCK_STREAM for connection-oriented protocols and SOCK_DGRAM for connectionless protocols.
3 protocol
Typically zero, this may be used to identify a variant of a protocol within a domain and type.
4 hostname
The identifier of a network interface −
A string, which can be a host name, a dotted-quad address, or an IPV6 address in colon (and possibly dot) notation
A string “”, which specifies an INADDR_BROADCAST address.
A zero-length string, which specifies INADDR_ANY, or
An Integer, interpreted as a binary address in host byte order.
5 port
Each server listens for clients calling on one or more ports. A port may be a Fixnum port number, a string containing a port number, or the name of a service.
The socket Module
To create a socket, you must use the socket.socket() function available in socket module, which has the general syntax −
s = socket.socket (socket_family, socket_type, protocol=0)
Here is the description of the parameters −
socket_family − This is either AF_UNIX or AF_INET, as explained earlier.
socket_type − This is either SOCK_STREAM or SOCK_DGRAM.
protocol − This is usually left out, defaulting to 0.
Once you have socket object, then you can use required functions to create your client or server program. Following is the list of functions required −
Server Socket Methods
Sr.No. Method & Description
1 s.bind()
This method binds address (hostname, port number pair) to socket.
2 s.listen()
This method sets up and start TCP listener.
3 s.accept()
This passively accept TCP client connection, waiting until connection arrives (blocking).
Client Socket Methods
Sr.No. Method & Description
1 s.connect()
This method actively initiates TCP server connection.
General Socket Methods
Sr.No. Method & Description
1 s.recv()
This method receives TCP message
2 s.send()
This method transmits TCP message
3 s.recvfrom()
This method receives UDP message
4 s.sendto()
This method transmits UDP message
5 s.close()
This method closes socket
6 socket.gethostname()
Returns the hostname.
A Simple Server
To write Internet servers, we use the socket function available in socket module to create a socket object. A socket object is then used to call other functions to setup a socket server.
Now call bind(hostname, port) function to specify a port for your service on the given host.
Next, call the accept method of the returned object. This method waits until a client connects to the port you specified, and then returns a connection object that represents the connection to that client.

!/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 = 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
A Simple Client
Let us write a very simple client program which opens a connection to a given port 12345 and given host. This is very simple to create a socket client using Python’s socket module function.
The socket.connect(hosname, port ) opens a TCP connection to hostnameon the port. Once you have a socket open, you can read from it like any IO object. When done, remember to close it, as you would close a file.
The following code is a very simple client that connects to a given host and port, reads any available data from the socket, and then exits −

!/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 = 12345 # Reserve a port for your service.

s.connect((host, port))
print s.recv(1024)
s.close() # Close the socket when done
Now run this server.py in background and then run above client.py to see the result.

Following would start a server in background.

$ python server.py &

Once server is started run client as follows:

$ python client.py
This would produce following result −
Got connection from (‘127.0.0.1’, 48437)
Thank you for connecting

Socket programming in Java [TCP]

Socket Programming in Java
This article describes a very basic one-way Client and Server setup where a Client connects, sends messages to server and the server shows them using socket connection. There’s a lot of low-level stuff that needs to happen for these things to work but the Java API networking package (java.net) takes care of all of that, making network programming very easy for programmers.
Client Side Programming
Establish a Socket Connection
To connect to other machine we need a socket connection. A socket connection means the two machines have information about each other’s network location (IP Address) and TCP port.The java.net.Socket class represents a Socket. To open a socket:
Socket socket = new Socket(“127.0.0.1”, 5000)
First argument – IP address of Server. ( 127.0.0.1  is the IP address of localhost, where code will run on single stand-alone machine).
Second argument – TCP Port. (Just a number representing which application to run on a server. For example, HTTP runs on port 80. Port number can be from 0 to 65535)
Communication

To communicate over a socket connection, streams are used to both input and output the data.
Closing the connection
The socket connection is closed explicitly once the message to server is sent.
In the program, Client keeps reading input from user and sends to the server until “Over” is typed.
Java Implementation
filter_none
edit
play_arrow
brightness_4
// A Java program for a Client
import java.net.; import java.io.;
  
public class Client
{
    // initialize socket and input output streams
    private Socket socket            = null;
    private DataInputStream  input   = null;
    private DataOutputStream out     = null;
  
    // constructor to put ip address and port
    public Client(String address, int port)
    {
        // establish a connection
        try
        {
            socket = new Socket(address, port);
            System.out.println(“Connected”);
  
            // takes input from terminal
            input  = new DataInputStream(System.in);
  
            // sends output to the socket
            out    = new DataOutputStream(socket.getOutputStream());
        }
        catch(UnknownHostException u)
        {
            System.out.println(u);
        }
        catch(IOException i)
        {
            System.out.println(i);
        }
  
        // string to read message from input
        String line = “”;
  
        // keep reading until “Over” is input
        while (!line.equals(“Over”))
        {
            try
            {
                line = input.readLine();
                out.writeUTF(line);
            }
            catch(IOException i)
            {
                System.out.println(i);
            }
        }
  
        // close the connection
        try
        {
            input.close();
            out.close();
            socket.close();
        }
        catch(IOException i)
        {
            System.out.println(i);
        }
    }
  
    public static void main(String args[])
    {
        Client client = new Client(“127.0.0.1”, 5000);
    }
}
Server Programming
Establish a Socket Connection
To write a server application two sockets are needed.
A ServerSocket which waits for the client requests (when a client makes a new Socket())
A plain old Socket socket to use for communication with the client.
Communication
getOutputStream() method is used to send the output through the socket.

Close the Connection
After finishing,  it is important to close the connection by closing the socket as well as input/output streams.
filter_none
edit
play_arrow
brightness_4
// A Java program for a Server
import java.net.; import java.io.;
  
public class Server
{
    //initialize socket and input stream
    private Socket          socket   = null;
    private ServerSocket    server   = null;
    private DataInputStream in       =  null;
  
    // constructor with port
    public Server(int port)
    {
        // starts server and waits for a connection
        try
        {
            server = new ServerSocket(port);
            System.out.println(“Server started”);
  
            System.out.println(“Waiting for a client …”);
  
            socket = server.accept();
            System.out.println(“Client accepted”);
  
            // takes input from the client socket
            in = new DataInputStream(
                new BufferedInputStream(socket.getInputStream()));
  
            String line = “”;
  
            // reads message from client until “Over” is sent
            while (!line.equals(“Over”))
            {
                try
                {
                    line = in.readUTF();
                    System.out.println(line);
  
                }
                catch(IOException i)
                {
                    System.out.println(i);
                }
            }
            System.out.println(“Closing connection”);
  
            // close connection
            socket.close();
            in.close();
        }
        catch(IOException i)
        {
            System.out.println(i);
        }
    }
  
    public static void main(String args[])
    {
        Server server = new Server(5000);
    }
}
Important Points
Server application makes a ServerSocket on a specific port which is 5000. This starts our Server listening for client requests coming in for port 5000.
Then Server makes a new Socket to communicate with the client.
socket = server.accept()
The accept() method blocks(just sits there) until a client connects to the server.
Then we take input from the socket using getInputStream() method. Our Server keeps receiving messages until the Client sends “Over”.
After we’re done we close the connection by closing the socket and the input stream.
To run the Client and Server application on your machine, compile both of them. Then first run the server application and then run the Client application.
To run on Terminal or Command Prompt
Open two windows one for Server and another for Client

  1. First run the Server application as ,
    $ java Server
    Server started
    Waiting for a client …
  2. Then run the Client application on another terminal as,
    $ java Client
    It will show – Connected and the server accepts the client and shows,
    Client accepted
  3. Then you can start typing messages in the Client window. Here is a sample input to the Client
    Hello
    I made my first socket connection
    Over
    Which the Server simultaneously receives and shows,
    Hello
    I made my first socket connection
    Over
    Closing connection
    Notice that sending “Over” closes the connection between the Client and the Server just like said before.
    If you’re using Eclipse or likes of such-
     Compile both of them on two different terminals or tabs
     Run the Server program first
     Then run the Client program
     Type messages in the Client Window which will be received and showed by the Server Window simultaneously.
     Type Over to end.

VLAN Configuration Using Cisco Packet Tracer

Creating a simple topology using packet tracer

Creating VLAN

Initial topology for the practice of VLAN, VTP, DTP and Router on Stick

SWITCH1

S1(config)#vlan 10
S1(config-vlan)#exit
S1(config)#vlan 20
S1(config-vlan)#exit
S1(config)#

Assigning VLAN Membership

switch1

S1(config)#interface fastEthernet 0/1
S1(config-if)#switchport access vlan 10
S1(config-if)#interface fastEthernet 0/2
S1(config-if)#switchport access vlan 20

switch2

S2(config)#interface fastEthernet 0/1
S2(config-if)#switchport access vlan 10
S2(config-if)#interface fastEthernet 0/2
S2(config-if)#switchport access vlan 20

switch3

S3(config)#interface fastEthernet 0/1
S3(config-if)#switchport access vlan 10
S3(config-if)#interface fastEthernet 0/2
S3(config-if)#switchport access vlan 20

Testing VLAN configuration

1] Access PC’s command prompt to test VLAN configuration. Double click PC-PT and click Command Prompt

A] VLAN10

VLAN Test

B] VLAN20

Test VLAN

Configure Router

Access command prompt of Router

To configure Router on Stick we have to access CLI prompt of Router. Click Router and Click CLI from menu items and Press Enter key to access the CLI

Run following commands in same sequence to configure Router

Router>enable
Router#configure terminal
Enter configuration commands, one per line.  End with CNTL/Z.
Router(config)#interface fastEthernet 0/0
Router(config-if)#no ip address
Router(config-if)#no shutdown
Router(config-if)#exit
Router(config)#interface fastEthernet 0/0.10
Router(config-subif)#encapsulation dot1Q 10
Router(config-subif)#ip address 10.0.0.1 255.0.0.0
Router(config-subif)#exit
Router(config)#interface fastEthernet 0/0.20
Router(config-subif)#encapsulation dot1Q 20
Router(config-subif)#ip address 20.0.0.1 255.0.0.0
Router(config-subif)#exit