You are on page 1of 37

UNP Lab

Table of Contents
S.No.

Content

Page No.

1.

Introduction to Network Programming

2.

TCP/IP Model vs. OSI Model

19

3.

Network Theory

23

4.

Program: Host Name And IP

25

5.

Program: Client Server Communication

29

6.

Program: Client Server Messaging

35

UNP Lab

LAB SESSION: 1 Introduction to Network Programming


When writing programs that communicate across a computer network, one must first invent a protocol, an agreement on how those programs will communicate. Before delving into the design details of a protocol, high- level decisions must be made about which program is expected to initiate communication and when responses are expected. For example, a Web server is typically thought of as a long-running program (or daemon) that sends network messages only in response to requests coming in from the network. The other side of the protocol is a Web client, such as a browser, which always initiates communication with the server. Clients normally communicate with one server at a time, although using a Web browser as an example, we might communicate with many different Web servers over, say, a 10- minute time period. But from the server's perspective, at any given point in time, it is not unusual for a server to be communicating with multiple clients.

Client Server Computing:


Client Process:This is the process which typically makes a request for information. After getting the response this process may terminate or may do some other processing. For example: Internet Browser works as a client application which sends a request to Web Server to get one HTML web page. Server Process:This is the process which takes a request from the clients. After getting a request from the client, this process will do required processing and will gather requested information and will send it to the requestor client. Once done, it becomes ready to serve another client. Server process are always alert and ready to serve incoming requests. For example: Web Server keeps waiting for requests from Internet Browsers and as soon as it gets any request from a browser, it picks up a requested HTML page and sends it back to that Browser.

2-tier and 3-tier architectures:


There are two types of client server architectures: 2-tier architectures: In this architecture, client directly interact with the server. This type of architecture may have some security holes and performance problems. Internet Explorer and Web Server works on two tier architecture. Here security problems are resolved using Secure Socket Layer(SSL). 3-tier architectures: In this architecture, one more software sits in between client and server. This middle software is called middleware. Middleware are used to
2

UNP Lab

perform all the security checks and load balancing in case of heavy load. A middleware takes all requests from the client and after doing req uired authentication it passes that request to the server. Then server does required processing and sends response back to the middleware and finally middleware passes this response back to the client. If you want to implement a 3-tier architecture then you can keep any middle ware like Web Logic or WebSphere software in between your Web Server and Web Browsers.

Types of Server:
There are two types of servers you can have: Iterative Server: This is the simplest form of server where a server process serves one client and after completing first request then it takes request from another client. Meanwhile another client keeps waiting. Concurrent Servers: This type of server runs multiple concurrent processes to serve many request at a time. Because one process may take longer and another client can not wait for so long. The simplest way to write a concurrent server under Unix is to fork a child process to handle each client separately.

How to make client:


The system calls for establishing a connection are so mewhat different for the client and the server, but both involve the basic construct of a socket. The two processes each establish their own sockets. The steps involved in establishing a socket on the client side are as follows: 1. Create a socket with the socket() system call. 2. Connect the socket to the address of the server using the connect() system call. 3. Send and receive data. There are a number of ways to do this, but the simplest is to use the read() and write() system calls.

How to make a server:


The steps involved in establishing a socket on the server side are as follows: 1. Create a socket with the socket() system call. 2. Bind the socket to an address using the bind() system call. For a server socket on the Internet, an address consists of a port number on the host machine. 3. Listen for connections with the listen() system call.

UNP Lab

4. Accept a connection with the accept() system call. This call typically blocks until a client connects with the server. 5. Send and receive data using the read() and write() system calls.

Client and Server Interaction:


Following is the diagram showing complete Client and Server interaction:

What is socket?
Sockets allow communication between two different processes on the same or different machines. To be more precise, it's a way to talk to other computers using standard Unix

UNP Lab

file descriptors. In Unix, every I/O actions are done by writing or reading to a file descriptor. A file descriptor is just an integer associated with an open file and it can be a network connection, a text file, a terminal, or something else.

Where socket is used?


A Unix Socket is used in a client server application frameworks. A server is a process which does some function on request from a client. Most of the application level protocols like FTP, SMTP and POP3 make use of Sockets to establish connection between client and server and then for exchanging data.

Socket Types:
There are four types of sockets available to the users. The first two are most commenly used and last two are rarely used. Stream Sockets: Delivery in a networked environment is guaranteed. If you send through the stream socket three items "A,B,C", they will arrive in the same order "A,B,C". These sockets use TCP (Transmission Control Protocol) for data transmission. If delivery is impossible, the sender receives an error indicator. Data records do no have any boundaries. Datagram Sockets: Delivery in a networked environment is not guaranteed. They're connectionless because you don't need to have an open connection as in Stream Sockets - you build a packet with the destination information and send it out. They use UDP (User Datagram Protocol). Raw Sockets: provides users access to the underlying communication protocols which support socket abstractions. These sockets are normally datagram oriented, though their exact characteristics are dependent on the interface provided by the protocol. Raw sockets are not intended for the general user; they have been provided mainly for those interested in developing new communication protocols, or for gaining access to some of the more esoteric facilities of an existing protocol. Sequenced Packet Sockets: They are similar to a stream socket, with the exception that record boundaries are preserved. This interface is provided only as part of the Network Systems (NS) socket abstraction, and is very important in most serious NS applications. Sequenced-packet sockets allow the user to manipulate the Sequence Packet Protocol (SPP) or Internet Datagram Protocol (IDP) headers on a packet or a group of packets either by writing a prototype header along with whatever data is to be sent.

Network Addresses - IP Addresses:


The IP host address, or more commonly just IP address, is used to identify hosts connected
5

UNP Lab

to the Internet. IP stands for Internet Protocol and refers to the Internet Layer of the overall network architecture of the Internet. An IP address is a 32-bit quantity interpreted as 4 8-bit numbers or octets. Each IP address uniquely identifies the participating user network, the host on the network, and the class of the user network. An IP address is usually written in a dotted-decimal notation of the form N1.N2.N3.N4, where each Ni is a decimal number between 0 and 255 decimal (00 through FF hexadecimal).

Address Classes:
IP addresses are managed and created by the Internet Assigned Numbers Authority (IANA). There are 5 different address classes. You can determine which class any IP address is in by examining the first 4 bits of the IP address. Class A addresses begin with 0xxx, or 1 to 126 decimal. Class B addresses begin with 10xx, or 128 to 191 decimal. Class C addresses begin with 110x, or 192 to 223 decimal. Class D addresses begin with 1110, or 224 to 239 decimal. Class E addresses begin with 1111, or 240 to 254 decimal. Addresses beginning with 01111111, or 127 decimal, are reserved for loopback and for internal testing on a local machine; [ You can test this: you should always be able to ping 127.0.0.1, which points to yourself ] Class D addresses are reserved for multicasting; Class E addresses are reserved for future use. They should not be used for host addresses.

Ports and Services:


When a client process wants to connect a server, the client must have a way of identifying the server that it wants to connect. SO if the client knows the 32-bit Internet address of the host on which the server resides it can contact that host. But how does the client identify the particular server process running on that host ? To resolve the problem of identifying a particular server process running on a host, both TCP and UDP have defined a group of well known ports. For our purposes, a port will be defined as an integer number between 1024 and 65535. This is because all port numbers smaller than 1024 are considered well-known -- for example, telnet uses port 23, http uses 80, ftp uses 21, and so on.

UNP Lab

The port assignments to network services can be found in the file /etc/services. If you are writing your own server then care must be taken to assign a port to your server. You should make sure that this port should already be not assigned to any other server.

Port and Service Functions:


Unix provides following functions to fetch service name from the /etc/services file. structservent *getservbyname(char *name, char *proto): - This call takes service name and protocol name and returns corresponding port number for that service. structservent *getservbyport(int port, char *proto): - This call takes port number and protocol name and returns corresponding service name. The return value for each function is a pointer to a structure with the following form: structservent { char *s_name; char **s_aliases; ints_port; char *s_proto; }; Here is the description of the member fields: Attribute Values s_name http Description This is official name of the service. For example SMTP, FTP POP3 etc. This will hold list of service aliases. Most of the time this will be set to NULL. This will have associated port number. For example for HTTP this will be 80. This will be set to the protocol used. Internet services are provided using either TCP or UDP.

s_aliases ALIAS

s_port

80 TCP UDP

s_proto

Byte Ordering Functions:


7

UNP Lab

unsignedshort htons(unsigned short hostshort) This function converts 16-bit (2-byte) quantities from host byte order to network byte order. unsigned long htonl(unsigned long hostlong) This function converts 32-bit (4-byte) quantities from host byte order to network byte order. unsigned short ntohs(unsigned short netshort) This function converts 16-bit (2-byte) quantities from network byte order to host byte order. unsigned long ntohl(unsigned long netlong) This function converts 32-bit quantities from network byte order to host byte order.

IP Address Functions:
UNIX provides various function calls that will help you manipulating IP addresses. These functions convert Internet addresses between ASCII strings (what humans prefer to use) and network byte ordered binary values (values that are stored in socket address structures). There are following three function calls which are used for IPv4 addressing: intinet_aton(const char *strptr, structin_addr *addrptr): This function call converts the specified string, in the Internet standard dot notation, to a network address, and stores the address in the structure provided. The converted address will be in Network Byte Order (bytes ordered from left to right). This returns 1 if string was valid and 0 on error. in_addr_tinet_addr(const char *strptr): This function call converts the specified string, in the Internet standard dot notation, to an integer value suitable for use as an Internet address. The converted address will be in Network Byte Order (bytes ordered from left to right). This returns a 32-bit binary network byte ordered IPv4 address and INADDR_NONE on error. char *inet_ntoa(structin_addrinaddr): This function call converts the specified Internet host address to a string in the Internet standard dot notation.

Socket Core Functions:


This tutorial describes the core socket functions required to write a complete TCP client and server. The socket Function:
8

UNP Lab

To perform network I/O, the first thing a process must do is call the socket function, specifying the type of communication protocol desired and protocol family etc. #include <sys/types.h> #include <sys/socket.h> int socket (int family, int type, int protocol); This call gives you a socket descriptor that you can use in later system calls or it gives you -1 on error. Parameters: family: specifies the protocol family and is one of the constants shown below: Family AF_INET AF_INET6 Description IPv4 protocols IPv6 protocols

AF_LOCAL Unix domain protocols AF_ROUTE Routing Sockets AF_KEY Ket socket

The connect Function: The connect function is used by a TCP client to establish a connection with a TCP server. #include <sys/types.h> #include <sys/socket.h> int connect(intsockfd, structsockaddr *serv_addr, intaddrlen); This call returns 0 if it successfully connects to the server otherwise it gives you -1 on error.

UNP Lab

Parameters:

sockfd: is a socket descriptor returned by the socket function. serv_addr is a pointer to structsockaddr that contains destination IP address and port. addrlen set it to sizeof(structsockaddr).

The bind Function: The bind function assigns a local protocol address to a socket. With the Internet protocols, the protocol address is the combination of either a 32-bit IPv4 address or a 128-bit IPv6 address, along with a 16-bit TCP or UDP port number. This function is called by TCP server only. #include <sys/types.h> #include <sys/socket.h> int bind(intsockfd, structsockaddr *my_addr,intaddrlen); This call returns 0 if it successfully binds to the address otherwise it gives you -1 on error. Parameters:

sockfd: is a socket descriptor returned by the socket function. my_addr is a pointer to structsockaddr that contains local IP address and port. addrlen set it to sizeof(structsockaddr).

The listen Function: The listen function is called only by a TCP server and it performs two actions:

The listen function converts an unconnected socket into a passive socket, indicating that the kernel should accept incoming connection requests directed to this socket. The second argument to this function specifies the maximum number of connections the kernel should queue for this socket.

#include <sys/types.h> #include <sys/socket.h>

10

UNP Lab

int listen(intsockfd,int backlog); This call returns 0 on success otherwise it gives you -1 on error. Parameters:

sockfd: is a socket descriptor returned by the socket function. backlog is the number of allowed connections.

The accept Function: The accept function is called by a TCP server to return the next completed connection from the front of the completed connection queue. If the completed connection queue is empty, the process is put to sleep.

The listen function converts an unconnected socket into a passive socket, indicating that the kernel should accept incoming connection requests directed to this socket. The second argument to this function specifies the maximum number of connections the kernel should queue for this socket.

#include <sys/types.h> #include <sys/socket.h> int accept (intsockfd, structsockaddr *cliaddr, socklen_t *addrlen); This call returns non negative descriptor on success otherwise it gives you -1 on error. The returned decriptor is assumed to be a client socket descriptor and all read write operations will be done on this descripton to communicate with the client. Parameters:

sockfd: is a socket descriptor returned by the socket function. cliaddr is a pointer to structsockaddr that contains client IP address and port. addrlen set it to sizeof(structsockaddr).

The send Function: The send function is used to send data over stream sockets or CONNECTED datagram sockets. If you want to send data over UNCONNECTED datagram sockets you must use sendto() function.

11

UNP Lab

You can use write() system call to send the data. This call is explained in helper functions tutorial. int send(intsockfd, const void *msg, intlen, int flags); This call returns the number of bytes sent out otherwise it will return -1 on error. Parameters:

sockfd: is a socket descriptor returned by the socket function. msg is a pointer to the data you want to send. len is the length of the data you want to send (in bytes). flags is set to 0.

The recv Function: The recv function is used to receive data over stream sockets or CONNECTED datagram sockets. If you want to receive data over UNCONNECTED datagram sockets you must use recvfrom(). You can use read() system call to read the data. This call is explained in helper functions tutorial. intrecv(intsockfd, void *buf, intlen, unsigned int flags); This call returns the number of bytes read into the buffer otherwise it will return -1 on error. Parameters:

sockfd: is a socket descriptor returned by the socket function. buf is the buffer to read the information into. len is the maximum length of the buffer. flags is set to 0.

The sendto Function: The sendto function is used to send data over UNCONNECTED datagram sockets. Put simply, when you use scoket type as SOCK_DGRAM

12

UNP Lab

intsendto(intsockfd, const void *msg, intlen, unsigned int flags, conststructsockaddr *to, inttolen); This call returns the number of bytes sent otherwise it will return -1 on error. Parameters:

sockfd: is a socket descriptor returned by the socket function. msg is a pointer to the data you want to send. len is the length of the data you want to send (in bytes). flags is set to 0. to is a pointer to structsockaddr for the host where data has to be sent. tolen is set it to sizeof(structsockaddr).

The recvfrom Function: The recvfrom function is used to receive data from UNCONNECTED datagra m sockets. Put simply, when you use scoket type as SOCK_DGRAM intrecvfrom(intsockfd, void *buf, intlen, unsigned int flags structsockaddr *from, int *fromlen); This call returns the number of bytes read into the buffer otherwise it will return -1 on error. Parameters:

sockfd: is a socket descriptor returned by the socket function. buf is the buffer to read the information into. len is the maximum length of the buffer. flags is set to 0. from is a pointer to structsockaddr for the host where data has to be read. fromlen is set it to sizeof(structsockaddr).

The close Function: The close function is used to close the communication between client and server. int close( intsockfd ); This call returns 0 on success otherwise it will return -1 on error.

13

UNP Lab

Parameters:

sockfd: is a socket descriptor returned by the socket function.

The shutdown Function: The shutdown function is used to gracefully close the communication between client and server. This function gives more control in caomparision of close function. int shutdown(intsockfd, int how); This call returns 0 on success otherwise it will return -1 on error. Parameters:

sockfd: is a socket descriptor returned by the socket function. how: put one of the numbers: o 0 indicates receives disallowed, o 1indicatesthat sends disallowed and o 2indicates that sends and receives disallowed. When how is set to 2, it's the same thing as close().

The select Function: The select function indicates which of the specified file descriptors is ready for reading, ready for writing, or has an error condition pending.

Socket Helper Functions:


This tutorial describes all the helper functions which are used while doing socket programming. Other helper functions are described in Ports and Services, Netowrk Byte Orders tutorials. The write Function: The write function attempts to write nbyte bytes from the buffer pointed to by buf to the file associated with the open file descriptor, fildes. You can also use send() function to send data to another process. #include <unistd.h>

14

UNP Lab

int write(intfildes, const void *buf, intnbyte); Upon successful completion, write() returns the number of bytes actually written to the file associated with fildes. This number is never greater than nbyte. Otherwise, -1 is returned, Parameters:

fildes: is a socket descriptor returned by the socket function. buf is a pointer to the data you want to send. nbyte is the number of bytes to be written. If nbyte is 0, write() will return 0 and have no other results if the file is a regular file; otherwise, the results are unspecified.

The read Function: The read function attempts to read nbyte bytes from the file associated with the open file descriptor, fildes, into the buffer pointed to by buf. You can also use recv() function to read data to another process. #include <unistd.h> int read(intfildes, const void *buf, intnbyte); Upon successful completion, write() returns the number of bytes actually written to the file associated with fildes. This number is never greater than nbyte. Otherwise, -1 is returned, Parameters:

fildes: is a socket descriptor returned by the socket function. buf is the buffer to read the information into.. nbyte is the number of bytes to read.

The fork Function: The fork function create a new process. The new process is called child process will be an exact copy of the calling process (parent process). The child process inherits many attributes from the parent process. #include <sys/types.h> #include <unistd.h>

15

UNP Lab

int fork(void); Upon successful completion, fork() return 0 to the child process and return the process ID of the child process to the parent process. Otherwise -1 is returned to the parent process, no child process is created and errno is set to indicate the error. Parameters:

void: means no parameter is required.

The bzero Function: The bzero function places nbyte null bytes in the string s. This function will be used to set all the socket structures with null values. void bzero(void *s, intnbyte); This function does not return anything. Parameters:

s: specifies string which has to be filled with null bytes.This will be a point to socket structure variable nbyte: specifies the number of bytes to be filled with null values. This will be the size of the socket structure.

The bcmp Function: The bcmp function compares byte string s1 against byte string s2. Both strings are assumed to be nbyte bytes long. intbcmp(const void *s1, const void *s2, intnbyte); This function returns 0 if both strings are identical, 1 otherwise. The bcmp() function always returns 0 when nbyte is 0. Parameters:

s1: specifies the first string to be compared. s2: specifies the second string to be compared. nbyte: specifies the number of bytes to be compared.
16

UNP Lab

The bcopy Function: The bcopy function copies nbyte bytes from string s1 to the string s2. Overlapping strings are handled correctly. void bcopy(const void *s1, void *s2, intnbyte); This function does not return anything. Parameters:

s1: specifies the source string. s2: specifies the destination string. nbyte: specifies the number of bytes to be copied.

The memset Function: The memset function is also used to set structure variables in the same way as bzero. void *memset(void *s, int c, intnbyte); This function returns a pointer to void, in fact pointer to the set memory and you need to caste it accordingly. Parameters:

s: specifies the source to be set. c: specifies the character to set on nbyte places.. nbyte: specifies the number of bytes to be set

Socket Server Function:


We have seen in one of the tutorials that to make a process a TCP server following steps are required: 1. Create a socket with the socket() system call. 2. Bind the socket to an address using the bind() system call. For a server socket on the Internet, an address consists of a port number on the host machine. 3. Listen for connections with the listen() system call.

17

UNP Lab

4. Accept a connection with the accept() system call. This call typically blocks until a client connects with the server. 5. Send and receive data using the read() and write() system calls.

Handle Multiple Connections:


To allow the server to handle multiple simultaneous connections, we make the following changes in the above code: 1. Put the accept statement and the following code in an infinite loop. 2. After a connection is established, call fork() to create a new process. 3. The child process will close sockfd and call doprocessing function, passing the new socket file descriptor as an argument. When the two processes have completed their conversation, as indicated by doprocessing() returning, this process simply exits. 4. The parent process closes newsockfd. Because all of this code is in an infinite loop, it will return to the accept statement to wait for the next connection.

Socket client function:


We have seen in one of the tutorials that to make a process a TCP client following steps are required: 1. Create a socket with the socket() system call. 2. Connect the socket to the address of the server using the connect() system call. 3. Send and receive data. There are a number of ways to do this, but the simplest is to use the read() and write() system calls.

18

UNP Lab

TCP/IP Model vs. OSI Model


TCP/IP model and the OSI model have been the two protocol suites on which the communication industry heavily relies on. Both TCP/IP model and OSI model work in a very similar fashion. But they do have very subtle differences too. Knowing these differences is very crucial to learning computer networking.

A Background:
OSI reference model came into existence way before the TCP/IP model was created. Advance research project agency (ARPA) created a (Department of Defence) DOD
19

UNP Lab

reference model so that they could logically group the similarly working components of the network into various layers of the protocol. Established in 1947, the International Standards Organization (ISO) is a multinational body dedicated to worldwide agreement on international standards. An ISO standard that covers all aspects of network communications is the Open Systems Interconnection (OSI) model. It was first introduced in the late 1970s.

20

UNP Lab

TCP/IP Model Layers Explained:


It is a suite of protocol which is named after its most significant pair of protocols. That is Transmission Control Protocol and Internet Protocol. TCP/IP are made up of layers. Each layer is responsible for a set of computer network related tasks. Every layer provides service to the layer above it. In all, there are four layers in the TCP/IP reference model. Application Layer: This is the topmost layer of the TCP/IP suite. The three topmost layers in the OSI model, however, are represented in TCP/IP by a single layer called the application layer. This is responsible for coding of the packet data. Transport Layer: This layer monitors end-to-end path selections of the packets. It also provides service to the application layer. Inte rnet Layer: This layer is responsible for sending packets through different networks. Link Layer: Last two layers in the OSI model, however, are represented in TCP/IP by a single layer called the link layer. It is the closest layer to the network hardware. It provides service to Internet layer.

OSI Model Layers Explained:


In OSI reference model there seven layers of protocols. Again, in OSI reference model, each layer provides services to the layer above it. These are all seven layers of OSI model. Physical Laye r: It is the lower most layer of the OSI reference model. It is layer which is responsible for direct interaction of the OSI model with hardware. The hardware provides service to the physical layer and it provides service to the data link layer. Data Link Layer: There may be certain errors which may occur at the physical layer. If possible, these errors are corrected by the data link layer. The data link layer provides the way by which various entities can transfer the data to the network. Network Layer: It does not allow the quality of the service to be degraded that was requested by the transport layer. It is also responsible for data transfer sequence from source to destination. Transport Layer: The reliability of the data is ensured by the transport layer. It also retransmits those data that fail to reach the destination. Session Layer: The session layer is responsible for creating and terminating the connection. Management of such a connection is taken care of by the session layer. Presentation Layer: This layer is responsible for decoding the context (syntax and semantics) of the higher level entities. Application Laye r: Whichever software application that implements socket programming will communicate with this layer. This layer is closest to the user.
20 Submitted By: Mithlesh Joshi

UNP Lab

TCP/IP Model vs. OSI Model:


The entire communication industry stands on the backbone of TCP/IP and OSI reference model. It is very vital to learn the above differences, if anyone wants to be an expert in the field of communication. Sr. No. 1 2 3 4 5 6 7

TCP/IP Reference Model Defined after the advent of Internet

OSI Reference Model Defined before advent of internet

Service interface and protocols were not clearly Service interface and protocols are distinguished before clearly distinguished TCP/IP supports Internet working Loosely layered Protocol Dependent standard More Credible Internet working not supported Strict layering Protocol independent standard Less Credible

TCP reliably delivers packets, IP does not All packets are reliably delivered reliably deliver packets

Difference between TCP and UDP:


Both TCP and UDP work at transport layer TCP/IP model, but have very different usage. The most important differences are explained below. Reliability : TCP: connection-oriented UDP: connectionless Ordered: TCP: order of message receipt is guaranteed UDP: order is not guaranteed Protocol we ight : TCP: heavyweight, because of the connection/ordering overhead UDP: lightweight, very few overhead Protocol used: TCP: Typical protocols which use TCP are HTTP, FTP and SMTP UDP: Examples of protocols using UDP are DNS and DHCP

UNP Lab

Packets : TCP: streaming, data is read as a "stream," with nothing distinguishing where one packet ends and another begins. There may be multiple packets per read call. UDP: datagram, one packet per one read call.

Frame Structure of TCP & UDP:


When data is sent over the network, it needs to be encapsulated into so called "frames". There are various methods of encapsulation depending on the protocol and topology that are being used. This is the TCP frame structure:

This is the UDP frame structure:

UNP Lab

LAB SESSION: 2 Network Theory


(1) PING: The ping command sends echo requests to the host you specify on the command line, and lists the responses received their round trip time. Simply use ping as: $ pingip_address or host_name 64 bytes from 8.3.1.5: icmp_seq=0 ttl=64 time=0.120 ms 64 bytes from 8.3.1.5: icmp_seq=1 ttl=64 time=0.050 ms --- 8.3.1.5 ping statistics --2 packets transmitted, 2 received, 0% packet loss, time 1000ms To stop ping use CTRL-C (break). ping command has various options : 1) -i interval $ping ipaddress - i 60 Here interval 60 specifies that, send one ICMP packet every 60 seconds. 2) -c count $ping ipaddress -c 3 The command will be terminated automatically after sending three ICMP packets to the requested host. It stops after sending 3 ECHO_REQUEST packets. 3) -s packetsize Specifies the number of data bytes to be sent. The default is 56, which translates into 64 ICMP data bytes when combined with the 8 bytes of ICMP header data. (2) IFCONFIG: This command is used to configure network interfaces, or to display their current configuration. If no arguments are given, ifconfig displays the status of the currently active interfaces. If a single interface argument is given, it displays the status of t he given interface only; if a single -a argument is given, it displays the status of all interfaces, even those that are down. We can use this command to activate and deactivate interfaces with the "up" and "down" settings. Examples: $ ifconfig //Displays information of all currently active interfaces $ ifconfig eth0 //Displays information of interface eth0 (Ethernet 0) only $ ifconfig -a //Displays information of all active as well as inactive interfaces Usually ifconfig lists following information about the interface. Interfaces that is currently up. Ethernet hardware address as well as inet (IP) address of the interface. Maximum Transmission Unit(MTU) Number of packets transmitted on the interface and number of packets received on the interface with all statistics. (3) TELNET: Telnet is a TCP/IP application that provides remote terminal services. Telnet allow a user from his or her network workstation to log in to a remote network station across

UNP Lab

the network and act as if the terminal station directly connected. The user starts the TELNET protocol at the terminal by typing telnet <domain name or IP address> $telnet 8.6.2.1 OR $telnet ninad The Telnet application would start and attempt to establish a connection to the remote device. If an argument was not supplied, TELNET would wait for the user to OPEN a connection using the DNS or IP address. (4) NETSTAT: Print network connections, routing tables, interface statistics and multicast memberships. By default, netstat displays a list of open sockets. If you dont specify any address families, then the active sockets of all configured address families will be printed. Various options can be used with netstatare : 1) -r $netstat -r //shows kernel IP routing table. 2) -i //provides information on the interface. 3) -t //Displays information of all TCP sockets 4) -u //Displays the information of all UDP sockets 5) x //Displays the information of all UNIX internal sockets. 6) -a //Your default netstat command does not display sockets that are in LISTENING mode. Use switch - a to display both listening and non-listening sockets. (5) TRACEROUTE: traceroute will actually show the route. It attempts to list the series of hosts through which your packets travel on their way to a given destination. It traces path to destination discovering MTU (Maximum Transmission Unit) along this path. $ tracepath 8.6.1.20 (6) RLOGIN: Stand for remote login. Rlogin command logs into a specified remote host and connects your local terminal to the remote host. Examples: To log in to a remote host with your local user name, enter: $rlogin host2 You are prompted to enter your password and then are logged in to the remote host host2. To logoff the remote host, and close the connection, enter ~. (tilde, period). To log into a remote host with a different user name, enter; $ rlogin host2 - l dale You are prompted to enter your password and then are logged in to the remote host host2 with the user name dale. To logoff the remote host, and close the connection, enter ~. (tilde, period).

UNP Lab

LAB SESSION: 3
Objective: Write a Program to Find out the Host Name and IP address of Host using Unix networking programming.

Host Name And IP


Host.c # include <stdio.h> # include <netdb.h> # include <netinet/in.h> # include <arpa/inet.h> int main() { char hostname[1024]; char *inputbuf; hostname[1023]='\0'; gethostname(hostname,1023); printf("Hostname:%s \n ", hostname); structhostent *h; h=gethostbyname(hostname); inputbuf=inet_ntoa(*((structin_addr *)h->h_addr_list[1])); printf("h_name: %s IP : %s", h->h_name, inputbuf); return 0; }

UNP Lab

UNP Lab

LAB SESSION: 4 Client Server Communication


Objective: Write a Program to de monstrate the client and server communication using Unix Socket programming. Client.c #include<sys/socket.h> #include<sys/types.h> #include<arpa/inet.h> #include<stdio.h> #include<netinet/in.h> #define ser_ip "127.0.0.1" #define port 3253 int main() { structsockaddr_incin; intclts,cltlen; clts=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); cin.sin_family=AF_INET; cin.sin_port=htons(port); cin.sin_addr.s_addr=inet_addr(ser_ip); cltlen=sizeof(cin); if(connect(clts,(structsockaddr*)&cin,cltlen)>=0) printf("Serve r connected"); else printf("Serve r not connected"); return 0; }

UNP Lab

Server.c #include<sys/socket.h> #include<sys/types.h> #include<arpa/inet.h> #include<stdio.h> #include<netinet/in.h> #define ser_ip "127.0.0.1" #define port 3253 int main() { structsockaddr_incin,sin; intsers,serlen,clts,cltlen; sers=socket(AF_INET,SOCK_STREAM,0); sin.sin_family=AF_INET; sin.sin_port=htons(port); sin.sin_addr.s_addr=inet_addr(ser_ip); serlen=sizeof(sin); cltlen=sizeof(cin); if(bind (sers, (structsockaddr *) &sin, serlen) < 0) { perror("Not Binded:\n"); } else printf("Binded and Wait for client...\n"); listen (sers,1 ); clts = accept (sers, (structsockaddr *) &cin, &cltlen); if(clts>=0) printf("Serve r connected"); else printf("Serve r not connected"); return 0; }

UNP Lab

UNP Lab

UNP Lab

LAB SESSION: 5 Client Server Messaging


Objective: Write a Program to demonstrate the client and server communication using Unix Socket programming. Sermsg.c #include<sys/socket.h> #include<sys/types.h> #include<arpa/inet.h> #include<stdio.h> #include<netinet/in.h> #include<stdlib.h> #include<string.h> #include<unistd.h> #define ser_ip "127.0.0.1" #define port 3253 int main() { structsockaddr_incin,sin; intsers,serlen,clts,cltlen,n; char msg1[100],msg2[100]; sers=socket(AF_INET,SOCK_STREAM,0); sin.sin_family=AF_INET; sin.sin_port=htons(port); sin.sin_addr.s_addr=inet_addr(ser_ip); serlen=sizeof(sin); cltlen=sizeof(cin); if(bind (sers, (structsockaddr *) &sin, serlen) < 0) { perror("Not Binded:\n"); } else printf("Binded and Wait for client...\n"); listen (sers,1 ); clts = accept (sers, (structsockaddr *) &cin, &cltlen); if(clts>=0) { do { fflush(stdin);

UNP Lab

n=read(clts,msg1,100); msg1[n]='\0'; printf("Client: %s\n",msg1); fflush(stdin); printf("Serve r: "); gets(msg2); printf("\n"); write(clts,msg2,100); }while((strcmp(msg2,"exit")!=0)&&(strcmp(msg2,"exit")!=0)); exit(1); } else printf("Serve r not connected"); return 0; } Clientmsg.c #include<sys/socket.h> #include<sys/types.h> #include<arpa/inet.h> #include<stdio.h> #include<netinet/in.h> #include<stdlib.h> #include<string.h> #include<unistd.h> #define ser_ip "127.0.0.1" #define port 3253 int main() { structsockaddr_incin,sin; intsers,serlen,clts,cltlen,n; char msg1[100],msg2[100]; sers=socket(AF_INET,SOCK_STREAM,0); sin.sin_family=AF_INET; sin.sin_port=htons(port); sin.sin_addr.s_addr=inet_addr(ser_ip); serlen=sizeof(sin); cltlen=sizeof(cin); if(bind (sers, (structsockaddr *) &sin, serlen) < 0) {

UNP Lab

perror("Not Binded:\n"); } else printf("Binded and Wait for client...\n"); listen (sers,1 ); clts = accept (sers, (structsockaddr *) &cin, &cltlen); if(clts>=0) { do { fflush(stdin); n=read(clts,msg1,100); msg1[n]='\0'; printf("Client: %s\n",msg1); fflush(stdin); printf("Serve r: "); gets(msg2); printf("\n"); write(clts,msg2,100); }while((strcmp(msg2,"exit")!=0)&&(strcmp(msg2,"exit")!=0)); exit(1); } else printf("Serve r not connected"); return 0; }

UNP Lab

UNP Lab

UNP Lab