Introduction to Socket programming using C



Similar documents
Socket Programming. Kameswari Chebrolu Dept. of Electrical Engineering, IIT Kanpur

Introduction to Socket Programming Part I : TCP Clients, Servers; Host information

Tutorial on Socket Programming

Implementing Network Software

Socket Programming. Srinidhi Varadarajan

Porting applications & DNS issues. socket interface extensions for IPv6. Eva M. Castro. ecastro@dit.upm.es. dit. Porting applications & DNS issues UPM

Socket Programming. Request. Reply. Figure 1. Client-Server paradigm

NS3 Lab 1 TCP/IP Network Programming in C

Unix Network Programming

INTRODUCTION UNIX NETWORK PROGRAMMING Vol 1, Third Edition by Richard Stevens

TCP/IP - Socket Programming

ELEN 602: Computer Communications and Networking. Socket Programming Basics

ICT SEcurity BASICS. Course: Software Defined Radio. Angelo Liguori. SP4TE lab.

CSE 333 SECTION 6. Networking and sockets

Network Programming with Sockets. Anatomy of an Internet Connection

Application Architecture

BSD Sockets Interface Programmer s Guide

Lab 4: Socket Programming: netcat part

UNIX Sockets. COS 461 Precept 1

IT304 Experiment 2 To understand the concept of IPC, Pipes, Signals, Multi-Threading and Multiprocessing in the context of networking.

VMCI Sockets Programming Guide VMware ESX/ESXi 4.x VMware Workstation 7.x VMware Server 2.0

The POSIX Socket API

Network Programming with Sockets. Process Management in UNIX

Socket Programming in C/C++

Overview. Socket Programming. Using Ports to Identify Services. UNIX Socket API. Knowing What Port Number To Use. Socket: End Point of Communication

Operating Systems Design 16. Networking: Sockets

Networks. Inter-process Communication. Pipes. Inter-process Communication

IBM i Version 7.2. Programming Socket programming IBM

Goal: learn how to build client/server application that communicate using sockets. An interface between application and network

Programmation Systèmes Cours 9 UNIX Domain Sockets

Networks class CS144 Introduction to Computer Networking Goal: Teach the concepts underlying networks Prerequisites:

Session NM059. TCP/IP Programming on VMS. Geoff Bryant Process Software

Communication Networks. Introduction & Socket Programming Yuval Rochman

Limi Kalita / (IJCSIT) International Journal of Computer Science and Information Technologies, Vol. 5 (3), 2014, Socket Programming

DESIGN AND IMPLEMENT AND ONLINE EXERCISE FOR TEACHING AND DEVELOPMENT OF A SERVER USING SOCKET PROGRAMMING IN C

Writing a C-based Client/Server

Hostnames. HOSTS.TXT was a bottleneck. Once there was HOSTS.TXT. CSCE515 Computer Network Programming. Hierarchical Organization of DNS

UNIX. Sockets. mgr inż. Marcin Borkowski

Client / Server Programming with TCP/IP Sockets

Writing Client/Server Programs in C Using Sockets (A Tutorial) Part I. Session Greg Granger grgran@sas. sas.com. SAS/C & C++ Support

Concurrent Server Design Alternatives

Network Programming TDC 561

Java Programming: Sockets in Java

An Introductory 4.4BSD Interprocess Communication Tutorial

Socket = an interface connection between two (dissimilar) pipes. OS provides this API to connect applications to networks. home.comcast.

Network Programming using sockets

Windows Socket Programming & IPv6 Translation Middleware

Socket programming. Socket Programming. Languages and Platforms. Sockets. Rohan Murty Hitesh Ballani. Last Modified: 2/8/2004 8:30:45 AM

First Workshop on Open Source and Internet Technology for Scientific Environment: with case studies from Environmental Monitoring

Packet Sniffing and Spoofing Lab

KATRAGADDA INNOVATIVE TRUST FOR EDUCATION NETWORK PROGRAMMING. Notes prepared by D. Teja Santosh, Assistant Professor, KPES, Shabad, R.R. District.

Lecture 17. Process Management. Process Management. Process Management. Inter-Process Communication. Inter-Process Communication

What is CSG150 about? Fundamentals of Computer Networking. Course Outline. Lecture 1 Outline. Guevara Noubir noubir@ccs.neu.

Lecture 7: Introduction to Sockets

Computer Networks/DV2 Lab

The exam has 110 possible points, 10 of which are extra credit. There is a Word Bank on Page 8. Pages 7-8 can be removed from the exam.

Chapter 3. Internet Applications and Network Programming

q Connection establishment (if connection-oriented) q Data transfer q Connection release (if conn-oriented) q Addressing the transport user

A Client-Server Transaction. Systemprogrammering 2006 Föreläsning 8 Network Programming. Hardware Org of a Network Host.

Division of Informatics, University of Edinburgh

Data Communication & Networks G

Computer Networks Network architecture

sys socketcall: Network systems calls on Linux

TCP/IP Sockets in C. Practical Guide for Programmers

System calls. Problem: How to access resources other than CPU

15-441: Computer Networks Homework 1

This tutorial has been designed for everyone interested in learning the data exchange features of Unix Sockets.

File Transfer And Access (FTP, TFTP, NFS) Chapter 25 By: Sang Oh Spencer Kam Atsuya Takagi

Elementary Name and Address. Conversions

IP Network Layer. Datagram ID FLAG Fragment Offset. IP Datagrams. IP Addresses. IP Addresses. CSCE 515: Computer Network Programming TCP/IP

Chapter 11. User Datagram Protocol (UDP)

IPv6 Enabling CIFS/SMB Applications

3.5. cmsg Developer s Guide. Data Acquisition Group JEFFERSON LAB. Version

Implementing and testing tftp

Lecture 9: Network Security Introduction

Objectives of Lecture. Network Architecture. Protocols. Contents

Java Network. Slides prepared by : Farzana Rahman

LESSON Networking Fundamentals. Understand TCP/IP

Overview of TCP/IP. TCP/IP and Internet

Abhijit A. Sawant, Dr. B. B. Meshram Department of Computer Technology, Veermata Jijabai Technological Institute

Linux MDS Firewall Supplement

Software changes for Website and Application IPv6 Readiness

Transport Layer Protocols

A Client Server Transaction. Introduction to Computer Systems /18 243, fall th Lecture, Nov. 3 rd

transmission media and network topologies client/server architecture layers, protocols, and sockets

TFTP Usage and Design. Diskless Workstation Booting 1. TFTP Usage and Design (cont.) CSCE 515: Computer Network Programming TFTP + Errors

Network Communication

A Heterogeneous Internetworking Model with Enhanced Management and Security Functions

SSL/TLS Programming. sslclient.c. /* A simple SSL client. It connects and then forwards data from/to the terminal to/from the server */

Linux MPS Firewall Supplement

Direct Sockets. Christian Leber Lehrstuhl Rechnerarchitektur Universität Mannheim

OS/390 Firewall Technology Overview

Transcription:

Introduction to Socket programming using C Goal: learn how to build client/server application that communicate using sockets Vinay Narasimhamurthy S0677790@sms.ed.ac.uk

CLIENT SERVER MODEL Sockets are used for interprocess communication. Most of the interprocess communication follow a Client-Server Model, where client and server are two separate processes in itself. Server and Client exchange messages over the network through a common Socket API Server ports Client user space TCP / UDP IP Socket API TCP / UDP IP kernel space Network Interface * Port numbers: 1,024 -- 65,535 (2 16-1) Network Interface hardware

Web server (port 80) FTP server (20, 21) Telnet server (23) Mail server (25) Server Examples

Client Examples Examples of client programs Web browsers, ftp, telnet, ssh How does a client find the server? The IP address in the server socket address identifies the host The (well-known) port in the server socket address identifies the service, and thus implicitly identifies the server process that performs that service. Examples of well know ports Port 7: Echo server Port 23: Telnet server Port 25: Mail server Port 80: Web server

What is an API? API expands as Application Programming Interface. A set of routines that an application uses to request and carry out lower-level services performed by a computer's operating system.

What is a socket? An interface between application and network which is used for communication between processes Once configured the application can pass data to the socket for network transmission receive data from the socket (transmitted through the network by some other host) To the kernel, a socket is an endpoint of communication. To an application, a socket is a file descriptor that lets the application read/write from/to the network. Clients and servers communicate with each by reading from and writing to socket descriptors. Remember: All Unix I/O devices, including networks, are modeled as files.

Two essential types of sockets SOCK_STREAM TCP connection-oriented reliable delivery in-order guaranteed bidirectional SOCK_DGRAM UDP no notion of connection app indicates dest. for each packet unreliable delivery no order guarantees can send or receive

What is a Port? A Port Number? Port numbers are used to identify services on a host Port numbers can be well-known (port 0-1023) dynamic or private (port 1024-65535) Servers/daemons usually use well-known ports any client can identify the server/service HTTP = 80, FTP = 21, Telnet = 23,... /etc/service defines well-known ports Clients usually use dynamic ports assigned by the kernel at run time Web Server TCP / UDP IP Server X 80 123 Network Interface

Connectionless sockets With connectionless sockets, it is possible for multiple processes to simultaneously send datagrams to the same socket established by a receiving process. Application 1 Gateway Server Application 2 datagram socket

Creating a Socket int socket(int family,int type,int proto); family specifies the protocol family (AF_INET for Internet, PF_INET for TCP/IP). type specifies the type of service (SOCK_STREAM, SOCK_DGRAM). protocol specifies the specific protocol (usually 0, which means the default).

socket() The socket() system call returns a socket descriptor (small integer) or -1 on error. socket() allocates resources needed for a communication endpoint - but it does not deal with endpoint addressing.

Generic socket addresses struct sockaddr { uint8_t sa_len; sa_family_t sa_family; char sa_data[14]; }; sa_family specifies the address type. sa_data specifies the address value.

struct sockaddr_in (IPv4) struct sockaddr_in { uint8_t sin_len; sa_family_t sin_family; in_port_t sin_port; struct in_addr sin_addr; char sin_zero[8]; }; A special kind of sockaddr structure

struct in_addr struct in_addr { }; in_addr_t s_addr; in_addr just provides a name for the C type associated with IP addresses.

Network Byte Order All values stored in asockaddr_in must be in network byte order. sin_port a TCP/IP port number. sin_addr an IP address.

Byte Ordering Big Endian Sun Solaris, PowerPC,... Little Endian i386, alpha,... Network byte order = Big Endian 128 2 194 95 95 194 2 128 c[0] c[1] c[2] c[3]

Assigning an address to a socket The bind() system call is used to assign an address to an existing socket. int bind( int sockfd, const struct sockaddr *myaddr, int addrlen); bind returns 0 if successful or -1 on error.

bind() calling bind() assigns the address specified by thesockaddr structure to the socket descriptor. You can give bind() asockaddr_in structure: bind( mysock, (struct sockaddr*) &myaddr, sizeof(myaddr) );

Uses for bind() There are a number of uses for bind(): Server would like to bind to a well known address (port number). Client can bind to a specific port. Client can ask the O.S. to assign any available port number.

What is my IP address? How can you find out what your IP address is so you can tell bind()? There is no realistic way for you to know the right IP address to give bind() - what if the computer has multiple network interfaces? specify the IP address as: INADDR_ANY, this tells the OS to take care of things.

Other socket system calls Connection-oriented oriented (TCP) connect() listen() accept() read() write() close() Connectionless (UDP) connect()* send() recv() sendto() recvfrom() * -optional but sometimes recommended

Methods : socket() Creates a new socket and returns its descriptor bind() Associates a socket with a port and address connect() Establish queue for connection requests listen() Accepts a connection request accept() Initiates a connection to a remote host recv() Receive data from a socket descriptor send() Sends data to a socket descriptor

Socket programming with TCP Client socket Server socket bind connect Connection request listen accept write read read write Await connection request from next client close close

Socket programming with UDP Client Server socket socket sendto bind recvfrom This is a blocking call and waits till it receives a request from the client recvfrom sendto close close

Example: C client (UDP) /* UDP client in the internet domain */ #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <stdio.h> void error(char *); int main(int argc, char *argv[]) { int sock, length, n; //socket structures struct sockaddr_in server, client; //hostent datastructure struct hostent *hp; char buffer[256]; if (argc!= 3) { printf("usage: server port\n"); exit(1); }

//specifies that it is a datagram socket //and the socket belongs to the INTERNET family sock= socket(af_inet, SOCK_DGRAM, 0); if (sock < 0) error("socket"); //We initialize the individual fields of the sockaddr_in structure //to fill sin_family which takes AF_INET as the value server.sin_family = AF_INET; //returns the hostname in the form of a hostent structure hp = gethostbyname(argv[1]); if (hp==0) error("unknown host"); //The below function can also be replaced with memcopy //but please never use strcpy() it wont work! bcopy((char *)hp->h_addr, (char *)&server.sin_addr, hp->h_length); //We initialize the individual fields of the sockaddr_in structure //to fill sin_port which takes the port number as the value //which was given as a command line parameter, remember to convert //this value into host to network byte order, it is very important! server.sin_port = htons(atoi(argv[2])); length=sizeof(struct sockaddr_in); printf("please enter the message: "); //This initializes the buffer with 0, we can also use memset as a replacement function

} bzero(buffer,256); //reads the value from the keyboard, stdin = keyboard fgets(buffer,255,stdin); //sends the buffer, to the server, the fourth parameter is by default zero. n=sendto(sock,buffer, strlen(buffer),0,&server,length); if (n < 0) error("sendto"); //receives the packet from the server which is stored in the buffer n = recvfrom(sock,buffer,256,0,&client, &length); if (n < 0) error("recvfrom"); write(1,"got an ack: ",12); write(1,buffer,n); //closes the socket descriptor close(sock); void error(char *msg) { perror(msg); exit(0); }

Example: C server (UDP) /* Creates a datagram server. The port number is passed as an argument. This server runs forever */ #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <stdio.h> void error(char *msg) { perror(msg); exit(0); } int main(int argc, char *argv[]) { int sock, length, clientlen, n; ///Declare the sockaddr_in structures for the client and the server struct sockaddr_in server; struct sockaddr_in client; char buf[1024];

if (argc < 2) { fprintf(stderr, "ERROR, no port provided\n"); exit(0); } ///The socket call which returns a file descriptor sock=socket(af_inet, SOCK_DGRAM, 0); if (sock < 0) error("opening socket"); length = sizeof(server); ///Initializes the server socket structure to zero, as a replacement we can also ///use memset bzero(&server,length); ///We initialize the values for all the individual fields of the server socket ///structure remember to make use of the INADDR_ANY to assign the ///sin_addr.s_addr field and please convert the port number obtained from the ///command line to network byte order server.sin_family=af_inet; server.sin_addr.s_addr=inaddr_any; server.sin_port=htons(atoi(argv[1])); ///bind system call if (bind(sock,(struct sockaddr *)&server,length)<0) error("binding"); clientlen = sizeof(struct sockaddr_in);

while (1) { ///ready to receive a packet from the client, the fourth parameter is by ///default zero n = recvfrom(sock,buf,1024,0,(struct sockaddr *)&client,&clientlen); if (n < 0) error("recvfrom"); //writes output to the screen write(1,"received a datagram: ",21); write(1,buf,n); //writes output to the screen ///sends a packet to the client acknowledging it n = sendto(sock,"got your message\n",17, 0,(struct sockaddr *)&client,clientlen); if (n < 0) error("sendto"); } ///closes the file descriptor close(sock); }

How to use Compile/Make? CC = gcc all: udpserver udpclient udpclient: udpclient.c $(CC) -o udpclient udpclient.c lnsl -<other compiler options> udpserver: udpserver.c $(CC) -o udpserver udpserver.c lnsl -<other compiler options> clean: rm udpserver udpclient Usage make f file_name <all> / clean

Suggestions Make sure to #include the header files that define used functions Check man-pages and course web-site for additional info Sometimes, a rough exit from a program (e.g., ctrl-c) does not properly free up a port Eventually (after a few minutes), the port will be freed To reduce the likelihood of this problem, include the following code: #include <signal.h> void cleanexit(){exit(0);} in socket code: signal(sigterm, cleanexit); signal(sigint, cleanexit); And, please keep backing up your files periodically!

Resources LINUX WORKSTATIONS ARE AVAILABLE AT THE UNIVERSITY COMPUTING LABS IN AT OR JCMB

For More Information Unix Man Pages Douglas Comer, "Computer Networks and Internets (4/e)", Pearson Education, 2004 W. Richard Stevens, Unix Network Programming: Networking APIs: Sockets and XTI, Volume 1, Second Edition, Prentice Hall, 1998. THE network programming bible.

For More Information The C Programming Language by Brian Kernighan and Dennis Ritchie, <http://cm.bell-labs.com/cm/cs/cbook/>. C for Java programmers http://www.cs.cornell.edu/courses/cs414/2001sp/tutorials/cforjava.htm For C programming FAQ s check <http://www.eskimo.com/~scs/c-faq/top.html> Web site which lists the differences between Java and C <http://www.comp.lancs.ac.uk/computing/users/ss/java2c/diffs.html> Some of these pointers to C are from Prof. Nigel Topham.