A. Basic Function Calls for Network Communications

Similar documents
Processes communicating. Network Communication. Sockets. Addressing processes 4/15/2013

Network Communication

CSE 124 Discussion Section Sockets Programming 10/10/17

Socket Programming for TCP and UDP

Chapter 6. The Transport Layer. Transport Layer 3-1

A Socket Example. Haris Andrianakis & Angelos Stavrou George Mason University

TCP: Three-way handshake

Lecture 2. Outline. Layering and Protocols. Network Architecture. Layering and Protocols. Layering and Protocols. Chapter 1 - Foundation

SOCKETS. COMP750 Distributed Systems

Socket Programming. CSIS0234A Computer and Communication Networks. Socket Programming in C

Review. Preview. Closing a TCP Connection. Closing a TCP Connection. Port Numbers 11/27/2017. Packet Exchange for TCP Connection

STUDY OF SOCKET PROGRAMMING

CSCE 463/612 Networks and Distributed Processing Spring 2017

UNIX Sockets. Developed for the Azera Group By: Joseph D. Fournier B.Sc.E.E., M.Sc.E.E.

UNIT IV- SOCKETS Part A

Oral. Total. Dated Sign (2) (5) (3) (2)

Unix Network Programming

Lecture 7. Followup. Review. Communication Interface. Socket Communication. Client-Server Model. Socket Programming January 28, 2005

WinSock. What Is Sockets What Is Windows Sockets What Are Its Benefits Architecture of Windows Sockets Network Application Mechanics

Outline. Distributed Computer Systems. Socket Basics An end-point for a IP network connection. Ports. Sockets and the OS. Transport Layer.

Introduction to Socket Programming

sottotitolo Socket Programming Milano, XX mese 20XX A.A. 2016/17 Federico Reghenzani

Ports under 1024 are often considered special, and usually require special OS privileges to use.

Outline. Operating Systems. Socket Basics An end-point for a IP network connection. Ports. Network Communication. Sockets and the OS

518 Lecture Notes Week 12

Outline. Distributed Computing Systems. Socket Basics (1 of 2) Socket Basics (2 of 2) 3/28/2014

Systems software design NETWORK COMMUNICATIONS & RPC SYSTEMS

Programming with TCP/IP. Ram Dantu

CS118 Discussion 1B, Week 1. Taqi Raza BUNCHE 1209B, Fridays 12:00pm to 1:50pm

EEC-484/584 Computer Networks

Group-A Assignment No. 6

CSCI 415 Computer Networks Homework 2 Due 02/13/08

EECS 123: Introduction to Real-Time Distributed Programming

Client-server model The course that gives CMU its Zip! Network programming Nov 27, Using ports to identify services.

Tutorial on Socket Programming

Simple network applications using sockets (BSD and WinSock) Revision 1 Copyright Clifford Slocombe

MSc Integrated Electronics Networks Assignment. Investigation of TCP/IP Sockets and Ports. Gavin Cameron

CS 640: Computer Networking

Department of Computer Science

Socket Programming TCP UDP

Introduction for SPI mapping Service Discovery Interoperability Testing. 20, Sep PWG Fumio Nagasaka

Sockets 15H2. Inshik Song

Sockets. Dong-kun Shin Embedded Software Laboratory Sungkyunkwan University Embedded Software Lab.

Introduction to Socket Programming

Networked Applications: Sockets. Goals of Todayʼs Lecture. End System: Computer on the ʻNet. Client-server paradigm End systems Clients and servers

Computer Network Lab, SS Fachgebiet Technische Informatik, Joachim Zumbrägel. Overview. Sockets. Sockets in C.

System Programming. Sockets

Winsock Server adding Multiple clients support C++

CSC209H Lecture 9. Dan Zingaro. March 11, 2015

Hyo-bong Son Computer Systems Laboratory Sungkyunkwan University

Internet protocol stack. Internetworking II: Network programming. April 20, UDP vs TCP. Berkeley Sockets Interface.

Ken French HELP Session 1 CS4514

Internetworking II: Network programming. April 20, 2000

CSE 333 Section 8 - Client-Side Networking

Client software design

Outline. Option Types. Socket Options SWE 545. Socket Options. Out-of-Band Data. Advanced Socket. Many socket options are Boolean flags

Server-side Programming

Communication. Sockets (Haviland Ch. 10)

Socket Programming. Sungkyunkwan University. Hyunseung Choo Copyright Networking Laboratory

// Embedded Systems // BeagleBoard-XM. // Author : Jose Goncalves //

Networked Applications: Sockets. End System: Computer on the Net

Server-side Programming

ECE 435 Network Engineering Lecture 2

Sockets. Jin-Soo Kim Computer Systems Laboratory Sungkyunkwan University

CS307 Operating Systems Processes

Processes. Process Concept. The Process. The Process (Cont.) Process Control Block (PCB) Process State

#1 socket_server.c socket_client.c

Network Programming November 3, 2008

Socket Programming. #In the name of Allah. Computer Engineering Department Sharif University of Technology CE443- Computer Networks

Elementary TCP Sockets

CSMC 412. Computer Networks Prof. Ashok K Agrawala Ashok Agrawala Set 2. September 15 CMSC417 Set 2 1

CSE 333 SECTION 8. Sockets, Network Programming

How do we Communicate? Introduction to Unix Network Programming. What does Alice do? What does Bob do? Two simplest networking programs

Overview. Administrative. * HW# 5 Due next week. * HW# 5 : Any Questions. Topics. * Client Server Communication. * 12.

What s an API? Do we need standardization?

CS4514 B08 HELP Session 1

NETWORK PROGRAMMING. Instructor: Junaid Tariq, Lecturer, Department of Computer Science

Lecture 7. Berkeley Socket Programming

CS 351 Week 15. Course Review

Windows Sockets: A Quick And Dirty Primer

Lab 0. Yvan Petillot. Networks - Lab 0 1

Application Programming Interfaces

CS4514 (C04) HELP Session 1 Introduction to Network Programming (v1.3)

Project 3. Reliable Data Transfer over UDP. NTU CSIE Computer Networks 2011 Spring

Hybrid of client-server and P2P. Pure P2P Architecture. App-layer Protocols. Communicating Processes. Transport Service Requirements

2007 Microsoft Corporation. All rights reserved.

Computer Networks Prof. Ashok K. Agrawala

ECE 435 Network Engineering Lecture 2

PA #2 Reviews. set_name, get_name, del_name. Questions? Will be modified after PA #4 ~

Multicast on a LAN 3/4. Multicast on a LAN 2/4. Multicast on a WAN. Multicast on a LAN 4/4

Lecture 5 Overview! Last Lecture! This Lecture! Next Lecture! I/O multiplexing! Source: Chapter 6 of Stevens book!

Introduction to Computer Networks

CS 43: Computer Networks. 05: Socket Programming September 12-14, 2018

Network Programming Worksheet 2. Simple TCP Clients and Servers on *nix with C.

CSE/EE 461 Lecture 14. Connections. Last Time. This Time. We began on the Transport layer. Focus How do we send information reliably?

Beej s Guide to Network Programming

CSE 333 SECTION 7. Client-Side Network Programming

Session NM056. Programming TCP/IP with Sockets. Geoff Bryant Process software

CSE 333 SECTION 7. C++ Virtual Functions and Client-Side Network Programming

Programming Ethernet with Socket API. Hui Chen, Ph.D. Dept. of Engineering & Computer Science Virginia State University Petersburg, VA 23806

Transcription:

IV. Network Programming A. Basic Function Calls for Network Communications 1

B. Settings for Windows Platform (1) Visual C++ 2008 Express Edition (free version) 2

(2) Winsock Header and Libraries Include WINSOCK2.H in your application; Link with WS2_32.LIB library. To compile a program, the steps are as follows: Click Tools menu > Options sub menu. 3

Expand Environment folder > Select Startup link > Set the At Startup: to Load last loaded solution > Click OK. 4

Then we can start creating the Win32 console application project. Click File menu > Project sub menu to create a new project. Select Win32 for the Project types: and Win32 Console Application for the Templates:. Put the project and solution name. Adjust the project location if needed and click OK. 5

Click Next for the Win32 Application Wizard Overview page. We will remove all the unnecessary project items. 6

In the Application page, select Empty project for the Additional options: Leave others as given and click Finish. 7

Next, we need to add new source file. Click Project menu > Add New Item sub menu or select the project folder in the Solution Explorer > Select Add menu > Select New Item sub menu. 8

Select C++ File (.cpp) for the Templates:. Put the source file name and click Add. Although the extension is.cpp, Visual C++ IDE will recognize that the source code used is C based on the Compile as C Code (/TC) option which will be set in the project property page later. 9

Add the source code Before we can build this Winsock C Win32 console application project, we need to set the project to be compiled as C code and link to ws2_32.lib, the Winsock2 library. Invoke the project property page. 10

Expand the Configuration folder > Expand the C/C++ sub folder. Select the Advanced link and for the Compile As option, select Compile as C Code (/TC). 11

Next, expand the Linker folder and select the Input link. For the Additional Dependencies option, click the ellipses at the end of the empty field on the right side. 12

You can just directly type the library name in the empty field on the right of the Additional Dependencies. Click OK. 13

Build the project and make sure there is no error which can be seen (if any) in the Output window normally docked at the bottom of the IDE by default, and then run the project If there is no error, a window will be popped out. 14

C. Introduction to Basic Functions (1) WSAStartup Function Program using Widows Sockets must call WSAstartup before using sockets. The call requires two arguments. The program uses the first to specify the version of Windows Sockets that is requested; the OS uses the second to return information about the version of Windows Sockets actually used. Syntax: int WSAStartup(WORD wversionrequested, LPWSADATA lpwsadata); Example: WSADATA wsadata; if (WSAStartup(0x202, &wsadata) == SOCKET_ERROR){ // stderr: standard error are printed to the screen. fprintf(stderr, "WSAStartup failed with error %d\n", WSAGetLastError()); //WSACleanup function terminates use of the Windows Sockets DLL. WSACleanup(); return -1; } 15

(2) WSACleanup Function Once an application finishes using and closing sockets, the application calls WSACleanup to de-allocate all data structures and socket bindings. Syntax: int WSACleanup(void); Example closesocket(msg_sock); WSACleanup(); (3) Creating a socket To create a socket, you can use the socket() function. Syntax: int socket(int af, int type, int protocol); 16

Example: int socket_desc; socket_desc=socket(af_inet,sock_stream,0); if (socket_desc==-1) perror("create socket"); socket() returns a socket descriptor which can be used in other network commands. If successful, socket() returns a valid socket descriptor; otherwise it returns -1. 17

(4) Binding a socket to a port With servers, the first socket created is often known as a "master socket". A master socket must be bound to a port number so that clients can know where to locate the socket and connect to it. Syntax: int bind(int s, struct sockaddr *addr, int addrlen); Example: struct sockaddr_in address; /* type of socket created in socket() */ address.sin_family = AF_INET; address.sin_addr.s_addr = INADDR_ANY; /* 7000 is the port to use for connections */ address.sin_port = htons(7000); /* bind the socket to the port specified above */ bind(socket_desc,(struct sockaddr *)&address,sizeof(address)); If successful, bind() returns 0; otherwise it returns -1. The port specified in the source code above (port 7000) is where the server can be connected to. 18

(5) Listening for connections Before any connections can be accepted, the socket must be told to listen for connections and also the maximum number of pending connections using listen() Syntax: int listen(int s, int backlog); Example: listen(socket_desc,3); The above line specifies that there can be up to 3 connections pending. Function listen() applies only to unconnected sockets of type SOCK_STREAM. If the socket has not been bound to a local port before listen() is invoked, the system automatically binds a local port for the socket to listen on. If successful, listen() returns 0; otherwise it returns -1. (6) Accepting a connection To tell the server to accept a connection, you have to use the function accept() Syntax: int accept(int s, struct sockaddr *addr, int *addrlen); 19

Example: int addrlen; struct sockaddr_in address; addrlen = sizeof(struct sockaddr_in); new_socket = accept(socket_desc, (struct sockaddr *)&address, &addrlen); if (new_socket<0) perror("accept connection"); accept() is used with connection based sockets such as streams. The parameters are the socket descriptor of the master socket followed by a sockaddr_in structure and the size of the structure. If successful, accept() returns a positive integer which is the socket descriptor for the accepted socket. If an error occurs, -1 is returned. (7) Closing connections A connection can be closed by using close(). Syntax: int close(int sockdes); Example: close(socket_desc); 20

close() closes the socket descriptor indicated by sockdes. Upon successful completion, close() returns a value of 0; otherwise, it returns -1. (8) Sending data to a connection Function send() is used to transmit a message to another socket and can be used only when the socket is in a connected state. Syntax: int send(int s, const void *msg, int len, int flags); Example: char *message="this is a message to send\n\r"; send(socket_desc,message,strlen(message),0); The message should have \n\r instead of just \n or \r because otherwise the text which appears on some clients may seem strange. The socket descriptor that specifies the socket on which the message will be sent is 's' in the syntax above. 'msg' points to the buffer containing the message and the length of the message is given by len, in bytes. The supported values for flags are zero, or MSG_OOB (to send out-of-band data). 21

Upon successful completion, send() returns the number of bytes sent. Otherwise, it returns -1. (9) Receiving data from a connection Accepting a connection would not be any use without the means to send or receive data. Receive only could be used as a data collection method. Syntax: int recv(int s, void *msg, int len, int flags); Example: int bufsize=1024; /* a 1K buffer */ char *buffer=malloc(bufsize); recv(socket_desc,buffer,bufsize,0); The flags parameter can be set to MSG_PEEK, MSG_OOB, both, or zero. If it is set to MSG_PEEK, any data returned to the user still is treated as if it had not been read, i.e the next recv() re-reads the same data. 22

If successful, recv() returns the number of bytes received, otherwise, it returns -1. recv() returns 0 if the socket is blocking and the connection to the remote node failed. (10) Setting socket options To allow certain socket operations requires manipulation of socket options using setsockopt() Syntax: int setsockopt(int s, int level, int optname, const void *optval, int optlen); Example: #define TRUE 1 #define FALSE 0 int socket_desc; /* master socket returned by socket() */ int opt=true; /* option is to be on/true or off/false */ setsockopt(socket_desc,sol_socket,so_reuseaddr, (char *)&opt,sizeof(opt)); 23

SOL_SOCKET specifies the option is a `socket level' option, these are defined in <sys/socket.h> The socket is identified by the socket descriptor s. The option SO_REUSEADDR is only valid for AF_INET sockets. There are two kinds of options: boolean and non-boolean. Boolean options are either set or not set and also can use optval and optlen to pass information. Nonboolean options always use optval and optlen to pass information. (11) Handling more than one connection To enable a socket to be read without waiting #include <process.h> i = 100; for(i = 0; i < 100; i ++) { _beginthread(accept_conn, 0, NULL ); }//for loop 24

_endthread(); // create a function to accept a connection void accept_conn(void *dummy) { // doing something here } (12) Converting a hostname into a network address Syntax: struct hostent *gethostbyname(const char *name); Example: struct hostent *hent; hent = gethostbyname("www.uic.edu.hk"); A hostent structure: struct hostent { char *h_name; /* official name of host */ 25

} char **h_aliases; /* alias list */ int h_addrtype; /* host address type */ int h_length; /* length of address */ char **h_addr_list; /* list of addresses */ Some of the network functions require a structure containing the network address and sometimes the port number to connect to or from. The easiest way to convert a hostname to a network address is to use the gethostbyname() function. gethostbyname() returns a structure of type hostent - this structure contains the name of the host, an array of alternative names and also an array of network addresses (in network byte order). 26

(13) Establishing an outgoing connection To establish a connection to another socket (similar to telnet), use the function connect(). int connect(int sockfd, struct sockaddr *serv_addr, int addrlen ); Create the socket using socket(), convert the hostname to an IP address using gethostbyname() and then issue the connect() call passing the relevant structures containing the IP address and port to connect to. struct hostent *he; struct sockaddr_in server; int sockfd; /* resolve localhost to an IP (should be 127.0.0.1) */ if ((he = gethostbyname("localhost")) == NULL) { printf("error resolving hostname.."); exit(1); } /* * copy the network address part of the structure to the * sockaddr_in structure which is passed to connect() 27

*/ memcpy(&server.sin_addr, he->h_addr_list[0], he->h_length); server.sin_family = AF_INET; server.sin_port = htons(7000); /* connect */ if (connect(sockfd, (struct sockaddr *)&server, sizeof(server)) { printf("error connecting.."); exit(1); } 28