Network Programming Using BSD sockets.

GLUG-T

- Manik (manickam@users.sf.net)

The slides are Licensed under GNU FDL

The OSI model (Open systems interconnection), Also known as the Wine glass model.

OSI describes the network activity as a structure having seven layers, with each having one or more protocols associated with it.

Application

Presentation

Session

Transport

Network

Data Link

Physical

This model was designed by the ISO. The number of protocols is the maximum for Application and physical layers.

Application Layer (user interface) :

Used for applications specifically written to run over the network

Allows access to network services that support applications

Directly represents the services that directly support user applications

Handles network access, flow control and error recovery

Example apps are file transfer,e-mail, NetBIOS-based applications

Protocols :

DNS; FTP; TFTP; BOOTP; SNMP;RLOGIN; SMTP; MIME; NFS; FINGER; TELNET; NCP; APPC; AFP; SMB

Presentation :

Translates from application to network format and vice-versa

All different formats from all sources are made into a common uniform format that the rest of the OSI model can understand

Responsible for protocol conversion, character conversion,data encryption decryption, expanding graphics commands, data compression.

Session :

Manages the connection and termination between computers involved.

Establishes, maintains and ends sessions across the network

Responsible for name recognition (identification) so only the designated parties can participate in the session

Provides synchronization services by planning check points in the data stream => if session fails, only data after the most recent checkpoint need be transmitted

Manages who can transmit data at a certain time and for how long

Examples are interactive login and file transfer connections, the session would connect and re-connect if there was an interruption; recognize names in sessions and register names in history

Protocols : NetBIOS, Names Pipes, Mail Slots, RPC .

Transport (flow control and error handling) :

Additional connection below the session layer .

Manages the flow control of data between parties across the network .

Divides streams of data into chunks or packets; the transport layer of the receiving computer reassembles the message from packets .

Provides error-checking to guarantee error-free data delivery, with on losses or duplications .

Provides acknowledgment of successful transmissions; requests retransmission if some packets don't arrive error-free .

Provides flow control and error-handling .

Protocols: TCP, ARP, RARP, SPX, NWLink, NetBIOS / NetBEUI, ATP.

Network :

Translates logical network address and names to their physical address (e.g. computername ==> MAC address)

Responsible for addressing

Determining routes for sending

Managing network problems such as packet switching, data congestion and routing

If router can't send data frame as large as the source computer sends, the network layer compensates by breaking the data into smaller units. At the receiving end, the network layer reassembles the data .

Protocols: IP, ARP, RARP, ICMP, RIP, OSFP, IGMP, IPX, NWLink, NetBEUI, OSI, DDP, DECnet .

DataLink (data frames to bits) :

Turns packets into raw bits 100101 and at the receiving end turns bits into packets.

Handles data frames between the Network and Physical layers

The receiving end packages raw data from the Physical layer into data frames for delivery to the Network layer

Responsible for error-free transfer of frames to other computer via the Physical Layer

This layer defines the methods used to transmit and receive data on the network. It consists of the wiring, the devices use to connect the NIC to the wiring, the signaling involved to transmit / receive data and the ability to detect signaling errors on the network media.

Protocols : Logic Link Control, CSMA/CD (ethernet), Token Bus and Token ring.

Physical (Hardware and raw bit stream):

Transmits raw bit stream over physical cable

Defines cables, cards, and physical aspects

Defines NIC attachments to hardware, how cable is attached to NIC

Defines techniques to transfer bit stream to cable

Protocols : IEEE 802, IEEE802.2, ISO 2110, ISDN.

Sockets :

Generalisation of an end point opened for communication.Sockets is a type of IPC mechanisms. In System V Unix, message queues, semaphores, and shared memory are examples of IPC mechanisms.

Comparision with file descriptor.

When open() sys call is used to open a file, an integer is returned, which is the file descriptor. Similar to that the socket() sys call returns a socket descriptor.

And the basic difference is that a file descriptor is connected to a specific end point(a file), whereas a socket descriptor is not connected to a specific end point.

read(),write(),close(), can be used for both the file descriptors and socket descriptors.

Opening a Socket :

A socket can be opened using the socket system call.

socket() takes in three arguments. (family,type,protocol)

Internet Address Family

AF_INET for communication between processes on the same or different systems using the (IP/UDP/TCP).

Type

SOCK_STREAM: A stream of data with no record boundaries. Delivery in a networked environment is guaranteed; if delivery is impossible, the sender receives an error indicator.

SOCK_DGRAM: A stream of records, each of a given size. Delivery in a networked environment is not guaranteed.

Protocol

Using multiple protocols like AF_IPX (indicating the Novell IPX protocol family) or AF_X25, indicating the old ITU X25 protocols.

bind()

The socket created is not connected to any end point. To do this the system call bind is used.

bind() takes two arguments (sock,port), and returns an integer.

int bind (int sockfd, struct sockaddr *myaddr, int addrlen);

Need of sockaddr structure.

Due to protocol independent design, the complexity increases. The address structure varies with protocols.

Hence, we use a common structure called sockaddr , and specifically for tcp/ip, we use sockaddr_in .The Internet socket address structure sockaddr_in is defined in <netinet/in.h>.

struct in_addr {

u_long s_addr; /*32-bit net id */

};

General Structure:

struct sockaddr {

u_short sa_family; /* address family; AF_xxx */

char sa_data[14]; /* protocol specific address */

};

struct sockaddr_in {

short sin_family; /* AF_INET */

u_short sin_port; /* 16-bit port number */

struct in_addr sin_addr; /* ip address */

char sin_zero[8]; /* unused */

};

#include<stdio.h>

#include<sys/types.h>

#include<sys/socket.h>

#include<netinet/in.h>

main()

{

int ssd,clsock,size,read_data=0;

pid_t pid;

static char x[20];

struct sockaddr_in servsock;

struct sockaddr claddr;

servsock.sin_addr.s_addr=INADDR_ANY;

servsock.sin_family=AF_INET;

servsock.sin_port=htons(55660);

bzero(&(servsock.sin_zero),8);

ssd=socket(AF_INET,SOCK_STREAM,0);

bind(ssd,(struct sockaddr *)&servsock,sizeof(struct sockaddr));

listen(ssd,5);

if (pid=fork()==0)

{

close(ssd);

perror("connection");

read_data=recv(clsock,&x,20,0);

send(clsock,&x,read_data,0);

puts(x);

exit(0);

}

close(clsock);

}

}

A Concurrent Echo server

A Serial Time Server:Python

#! /usr/bin/python

import socket

import time

import os

class server:

"""This is the messiest class you can ever imagine!! """

def __init__(self,portname,service,max_limit):

"""The Server that cannot suck"""

self.servic=service

self.port=portname

self.max_limit=max_limit

self.sock_create_bind_listen();

self.accept_handle();

def sock_create_bind_listen(self):

self.socket=socket.socket(socket.AF_INET,socket.SOCK_STREAM,0)

self.socket.bind(("localhost",self.port))

self.socket.listen(self.max_limit)

def accept_handle(self):

"""This is to handle the process"""

while(1):

"""wait indefnitely and handle synchronously"""

(self.client,self.addr)=self.socket.accept()

self.curr_time=time.ctime()

self.client.send(self.curr_time)

print self.client.recv(1000)

self.client.close()

del self.client

def shutdown(self):

self.socket.shutdown(0);

del self.socket

from sys import exit

exit(0)

if ( __name__ == "__main__"):

ser=server(9090,"Date and Time",10);

A SMTP client

#! /usr/bin/python

import socket

class Mail:

def __init__(self):

self.sock=None

def make_socket(self):

sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM,0)

sock.connect(("localhost",25))

reply=sock.recv(1000) #clear the first dump

print reply

return sock

def main(self):

self.sock=self.make_socket();

sock=self.sock;

to=raw_input("Enter Return address")

frm=raw_input("Enter Destination address")

print "MAIL ing"

sock.send("MAIL FROM:<"+frm+">\r\n")

reply=sock.recv(1000 )

print reply

print "RCPT ing"

sock.send("RCPT TO:<"+to+">\r\n")

reply=sock.recv(1000 )

print reply

print "DATA sending"

sock.send("DATA\r\n")

reply=sock.recv(1000 )

print reply

data=raw_input("Enter Data to be sent")

sock.send(data)

sock.send("\r\n.\r\n")

reply=sock.recv(1000 )

print reply

sock.send("QUIT\r\n")

print sock.recv(1000 )

sock.close()

if __name__=="__main__":

m=Mail()

m.main()

Thank You!

2005-02-26T15:50:53