Transcription

NETWORK PROGRAMMING LAB MANUAL1. Understanding and using of commands like ifconfig, netstat, ping, arp, telnet, ftp, finger,traceroute, whois etc. Usage of elementary socket system calls (socket (), bind(), ,recvfrom()).Program Objective:Understanding and using of commands like ifconfig, netstat, ping, arp, telnet, ftp, finger,traceroute, whoisProgram Description:UNIX utilities are commands that, generally, perform a single task. It may be as simple as printingthe date and time, or a complex as finding files that match many criteria throughout a directoryhierarchyIFCONFIGThe Unix command ifconfig (short for interface configurator) serves to configure and controlTCP/IP network interfaces from a command line interface (CLI).Common uses for ifconfig include setting an interface's IP address and netmask, and disabling orenabling a given interface.Ipconfig is an MS-DOS utility that can be used from MS-DOS and an MS-DOS shell to displaythe network settings currently assigned and given by a network. This command can be utilized toverify a network connection as well as to verify your network settings.Syntax: ipconfig [/allcompartments] [/? /all /renew [adapter] /release [adapter] /renew6[adapter] /release6 [adapter] /flushdns /displaydns /registerdns /showclassid adapter /setclassid adapter [classid] /showclassid6 adapter /setclassid6 adapter [classid] ]Example: ipconfig /allOutput:

NETSTATnetstat (network statistics) is a command-line tool that displays network connections (bothincoming and outgoing), routing tables, and a number of network interface statistics.It is used for finding problems in the network and to determine the amount of traffic on the networkas a performance measurement.ParametersParameters used with this command must be prefixed with a hyphen (-) rather than a slash (/).-a : Displays all active TCP connections and the TCP and UDP ports on which the computer islistening.-e : Displays ethernet statistics, such as the number of bytes and packets sent and received. Thisparameter can be combined with -s.-f : Displays fully qualified domain names FQDN for foreign addresses.-i : Displays network interfaces and their statistics (not available under Windows)-n : Displays active TCP connections, however, addresses and port numbers are expressednumerically and no attempt is made to determine names.-o : Displays active TCP connections and includes the process ID (PID) for each connection.-p Linux: Process : Show which processes are using which socketsSyntax: NETSTAT [-a] [-b] [-e] [-f] [-n] [-o] [-p proto] [-r] [-s] [-x] [-t] [interval]Output:

PINGPing is a computer network tool used to test whether a particular host is reachable across an IPnetwork; it is also used to self test the network interface card of the computer, or as a speed test. Itworks by sending ICMP “echo request” packets to the target host and listening for ICMP “echoresponse” replies. Ping does not estimate the round-trip time, as it does not factor in the user'sconnection speed, but instead is used to record any packet loss, and print a statistical summarywhen finished.The word ping is also frequently used as a verb or noun, where it is usually incorrectly used torefer to the round-trip time, or measuring the round-trip time.Syntax: ping [-t] [-a] [-n count] [-l size] [-f] [-i TTL] [-v TOS] [-r count] [-s count] [[-j host-list] [-k host-list]] [-w timeout] [-R] [-S srcaddr] [-4] [-6 target name]Output:ARPIn computer networking, the Address Resolution Protocol (ARP) is the method for finding ahost's link layer (hardware) address when only its Internet Layer (IP) or some other Network Layeraddress is known.ARP has been implemented in many types of networks; it is not an IP-only or Ethernet-onlyprotocol. It can be used to resolve many different network layer protocol addresses to interfacehardware addresses, although, due to the overwhelming prevalence of IPv4 and Ethernet, ARP isprimarily used to translate IP addresses to Ethernet MAC addresses.Arp syntax:

ARP -s inet addr eth adr [if addr]ARP -d inet addr [if addr]ARP -a [inet addr] [-N if addr]Example: arp -aOutput:TELNETTelnet (Telecommunication network) is a network protocol used on the Internet or local areanetwork (LAN) connections.Typically, telnet provides access to a command-line interface on a remote machine.The term telnet also refers to software which implements the client part of the protocol. Telnetclients are available for virtually all platformsProtocol details:Telnet is a client-server protocol, based on a reliable connection-oriented transport. Typically thisprotocol is used to establish a connection to TCP port 23Syntax: telnet [-468ELadr] [-S tos] [-b address] [-e escapechar] [-l user] [-n tracefile] [host [port]]Example: telnet myhost.com

FTPFile Transfer Protocol (FTP):FTP is a network protocol used to transfer data from one computer to another through a networksuch as the Internet.FTP is a file transfer protocol for exchanging and manipulating files over aTCP computer network. An FTP client may connect to an FTP server to manipulate files on thatserver.FTP runs over TCP. It defaults to listen on port 21 for incoming connections from FTPclients. A connection to this port from the FTP Client forms the control stream on which commandsare passed from the FTP client to the FTP server and on occasion from the FTP server to the FTPclient. FTP uses out-of-band control, which means it uses a separate connection for control anddata. Thus, for the actual file transfer to take place, a different connection is required which iscalled the data stream.Syntax: ftp [-46pinegvd] [host [port]]Example: ftp exampleftp.computerhope.comFINGER:In computer networking, the Name/Finger protocol and the Finger user information protocolare simple network protocols for the exchange of human-oriented status and user information.finger looks up and displays information about system users.Syntax: finger [-lmsp] [user .] [[email protected] .]Example: finger -p chTRACEROUTE:traceroute is a computer network tool used to determine the route taken by packets across an IPnetwork . An IPv6 variant, traceroute6, is also widely available.Traceroute is often used fornetwork troubleshooting. By showing a list of routers traversed, it allows the user to identify thepath taken to reach a particular destination on the network. This can help identify routing problemsor firewalls that may be blocking access to a site. Traceroute is also used by penetration testers togather information about network infrastructure and IP ranges around a given host. It can also beused when downloading data, and if there are multiple mirrors available for the same piece of data,one can trace each mirror to get a good idea of which mirror would be the fastest to use.Syntax: traceroute [-46dFITUnreAV] [-f first ttl] [-g gate,.] [-i device][-m max ttl] [-p port] [-s src addr] [-q nqueries][-N squeries] [-t tos] [-l flow label] [-w waittime][-z sendwait] [-UL] [-D] [-P proto] [--sport port] [-M method]

[-O mod options] [--mtu] [--back] host [packet len]Example: traceroute www.google.comWHO IS:WHOIS (pronounced "who is"; not an acronym) is a query/response protocol which is widelyused for querying an official database in order to determine the owner of a domain name, an IPaddress, or an autonomous system number on the Internet. WHOIS lookups were traditionallymade using a command line interface, but a number of simplified web-based tools now exist forlooking up domain ownership details from different databases. WHOIS normally runs on TCP port43.The WHOIS system originated as a method that system administrators could use to look upinformation to contact other IP address or domain name administrators (almost like a "whitepages").Syntax: whois [ -h HOST ] [ -p PORT ] [ -aCFHlLMmrRSVx ] [ -g SOURCE:FIRST-LAST ] [ -iATTR ] [ -S SOURCE ] [ -T TYPE ] objectExample: whois www.google.comsocketTo do network I/O, the first thing a process must do is to call the socket system call, nclude sys/types.h #include sys/socket.h int socket(int family, int type, int protocol);The family isoneAF UNIX-- Unix internal protocolsAF INET-- Internet protocolsAF NS-- Xerox NS ProtocolsofAF IMPLINK -- IMP link layerThe AF prefix stands for "address family." In the first project, we are going to use AF INET.

Thesocket type isoneSOCK STREAMstream socketSOCK DGRAMdatagram socketofthefollowing:SOCK RAW raw socketSOCK SEQPACKET sequenced packet socketSOCK RDM reliably delivered message socket (not implemented yet)The protocol argument to the socket system call is typically set to 0 for most user applications.The valid combinations are shown as follows.familytypeprotocolActual protocolAF INET SOCK DGRAM IPPROTO UDP UDPAF INET SOCK STREAM IPPROTO TCP TCPAF INET SOCK RAWIPPROTO ICMP ICMPAF INET SOCK RAWIPPROTO RAW (raw)/* A program to create a socket using socket systemcall*/#include stdio.h #include sys/socket.h #include sys/types.h #include netinet/in.h #include stdlib.h int main(){int sfd,n,len,s,nsfd,i;struct sockaddr in sa;if((sfd socket(AF INET,SOCK STREAM,0)) 0){

perror("socket error");exit(-1);}printf("\n SOCKET CREATED.");close(sfd);return 0;}O/P: SOCKET CREATED.bindThe bind systemcall#include sys/types.h #include sys/socket.h assignsanametoanunnamedsocket.int bind(int sockfd, struct sockaddr *myaddr, int addrlen);The first argument is the socket descriptor returned from socket system call. The second argumentis a pointer to a protocol-specific address and the third argument is the size of this address. Therearethreeusesof bind.1. Servers register their well-known address with the system. It tells the system "this is myaddress and any messages received for this address are to be given to me." Both connectionoriented and connectionless servers need to do this before accepting client requests.2. A client can register a specific address for itself.3. A connectionless client needs to assure that the system assigns it some unique address, sothat the other end (the server) has a valid return address to send its responses to. Thiscorresponds to making certain an envelope has a valid return address, if we expect to get areply from the person we sent the letter to.//program to implement to a binding#include stdio.h #include sys/socket.h #include sys/types.h #include netinet/in.h

#include stdlib.h int main(){int sfd;struct sockaddr in serv addr;if((sfd socket(AF INET,SOCK STREAM,0)) 0){perror("socket error");exit(-1);}serv addr.sin family AF INET;serv addr.sin port htons(4890);serv addr.sin addr.s addr inet addr("172.16.0.1");if((bind(sfd,(struct sockaddr *) & serv addr,sizeof(serv addr))) 0){perror("bind error");exit(-1);}printf("address binded.");printf("\nserver ip address is %s",inet ntoa(serv addr.sin addr));printf("\n port number %d\n",ntohs(serv addr.sin port));close(sfd);return 0;}O/P:address binded.server ip address is 172.16.0.1portnumber 4890

connectA client process connects a socket descriptor following the socket system call to establish aconnectionwithaserver.#include sys/types.h #include sys/socket.h int connect(int sockfd, struct sockaddr *servaddr, int addrlen);The sockfd is a socket descriptor that was returned by the socket system call. The second and thirdarguments are a pointer to a socket address, and its size, as described earlier.For most connection-oriented protocols (TCP, for example), the connect system call results in theactual establishment of a connection between the local system and the foreign system.The connect system call does not return until the connection is established, or an error is returnedtotheprocess.The client does not have to bind a local address before calling connect. The connection typicallycauses these four elements of the association 5-tuple to be assigned: local-addr, localprocess,foreign-addr, and foreign-process. In all the connection-oriented clients, we willlet connect assignthelocaladdress.listenThis system call is used by a connection-oriented server to indicate that it is willing to receiveconnections.#include sys/types.h #include sys/socket.h int listen(int sockfd, int backlog);It is usually executed after both the socket and bind system calls, and immediately beforethe accept system call. The backlog argument specifies how many connection requests can bequeued by the system while it waits for the server to execute the accept system call. This ntlyallowed.acceptAfter a connection-oriented server executes the listen system call described above, an actualconnection from some client process is waited for by having the server execute the accept system

call.#include sys/types.h #include sys/socket.h int accept(int sockfd, struct sockaddr *peer, int *addrlen);accept takes the first connection request on the queue and creates another socket with the sameproperties as sockfd. If there are no connection requests pending, this call blocks the caller untilonearrives.The peer and addrlen arguments are used to return the address of the connected peer process (theclient). addrlen is called a value-result argument: the caller sets its value before the system call,and the system call stores a result in the variable. For this system call the caller sets addrlen to thesize of the sockaddr structure whose address is passed as the peer argument.send, sendto, recv and recvfromThese system calls are similar to the standard read and write system calls, but additionalargumentsarerequired.#include sys/types.h #include sys/socket.h int send(int sockfd, char *buff, int nbytes, int flags);int sendto(int sockfd, char *buff, int nbytes, int flags, struct sockaddr *to, int addrlen);int recv(int sockfd, char *buff, int nbytes, int flags);int recvfrom(int sockfd, char *buff, int nbytes, int flags, struct sockaddr *from, int *addrlen);The first three arguments, sockfd, buff, and nbytes, to the four system calls are similar to the firstthree arguments for read and write. The flags argument can be safely set to zero ignoring thedetails for it. The to argument for sendto specifies the protocol-specific address of where the datais to be sent. Since this address is protocol-specific, its length must be specified by addrlen.Therecvfrom system call fills in the protocol-specific address of who sent the data into from. Thelength of this address is also returned to the caller in addrlen. Note that the final argumentto sendtois an integer value, while the final argument to recvfrom is a pointer to an integer value.close

ThenormalUnix close systemcallisalsousedtocloseasocket.int close(int fd);If the socket being closed is associated with a protocol that promises reliable delivery (e.g., TCPor SPP), the system must assure that any data within the kernel that still has to be transmitted oracknowledged, is sent. Normally, the system returns from the close immediately, but the kernelstill tries to send any data already queued.

FTP File Transfer Protocol (FTP): FTP is a network protocol used to transfer data from one computer to another through a network such as the Internet.FTP is a file transfer protocol for exchanging and manipulating files over a TCP computer network. An FTP client may connect to an FTP server to manipulate files on that