1 JMH Associates © 2000, All rights reserved Chapter 12 Windows Sockets and Network Programming.

Slides:



Advertisements
Similar presentations
Computer Net Lab/Praktikum Datenverarbeitung 2 1 Overview Sockets Sockets in C Sockets in Delphi.
Advertisements

Sockets: Network IPC Internet Socket UNIX Domain Socket.
Socket Programming Application Programming Interface.
Networks: TCP/IP Socket Calls1 Elementary TCP Sockets Chapter 4 UNIX Network Programming Vol. 1, Second Ed. Stevens.
Windows Sockets Purpose Windows Sockets 2 (Winsock) enables programmers to create advanced internet, intranet, and other network-capable applications to.
Tutorial 8 Socket Programming
Programming with Berkeley Sockets Presented by Chris GauthierDickey Written by Daniel Stutzbach (I think!) for CIS 432/532 Useful References: ● man pages.
CS 311 – Lecture 18 Outline IPC via Sockets – Server side socket() bind() accept() listen() – Client side connect() Lecture 181CS Operating Systems.
Socket Addresses. Domains Internet domains –familiar with these Unix domains –for processes communicating on the same hosts –not sure of widespread use.
CSE/EE 461 Getting Started with Networking. Basic Concepts  A PROCESS is an executing program somewhere.  Eg, “./a.out”  A MESSAGE contains information.
Winsock programming.  TCP/IP UDP TCP  Winsock #include wsock32.lib.
ISP – 9 th Recitation Socket programming – Client side.
1 Tutorial on Socket Programming Computer Networks - CSC 458 Department of Computer Science Yukun Zhu (Slides are mainly from Monia Ghobadi, and Amin Tootoonchian,
Client Software Design Objectives: Understand principles of C/S design, with focus on clients Review Windows implementations of Socket functions.
Socket Programming References: redKlyde ’ s tutorial set Winsock2 for games (gamedev.net)
ECE 4110 – Internetwork Programming Client-Server Model.
Assignment 3 A Client/Server Application: Chatroom.
Network Programming Tutorial #9 CPSC 261. A socket is one end of a virtual communication channel Provides network connectivity to any other socket anywhere.
Socket Programming. Introduction Sockets are a protocol independent method of creating a connection between processes. Sockets can be either – Connection.
CS345 Operating Systems Φροντιστήριο Άσκησης 2. Inter-process communication Exchange data among processes Methods –Signal –Pipe –Sockets.
9/12/2015B.R1 Socket Abstraction and Interprocess Communication B.Ramamurthy CSE421.
Server Sockets: A server socket listens on a given port Many different clients may be connecting to that port Ideally, you would like a separate file descriptor.
 Wind River Systems, Inc Chapter - 13 Network Programming.
Windows Network Programming ms-help://MS.MSDNQTR.2004JAN.1033/winsock/winsock/windows_sockets_start_page_2.htm 井民全.
Chapter 2 Applications and Layered Architectures Sockets.
The Socket Interface Chapter 21. Application Program Interface (API) Interface used between application programs and TCP/IP protocols Interface used between.
The Socket Interface Chapter 22. Introduction This chapter reviews one example of an Application Program Interface (API) which is the interface between.
Network Programming Eddie Aronovich mail:
Remote Shell CS230 Project #4 Assigned : Due date :
Windows Operating System Internals - by David A. Solomon and Mark E. Russinovich with Andreas Polze Unit OS A: Windows Networking A.2. Windows Sockets.
Outline Socket programming with Windows OSSocket programming with Windows OS C++ UDPSocket classC++ UDPSocket class Socket programming with Windows OSSocket.
CS 158A1 1.4 Implementing Network Software Phenomenal success of the Internet: – Computer # connected doubled every year since 1981, now approaching 200.
CPSC 441 TUTORIAL – FEB 13, 2012 TA: RUITNG ZHOU UDP REVIEW.
1 Computer Networks An Introduction to Computer Networks University of Tehran Dept. of EE and Computer Engineering By: Dr. Nasser Yazdani Lecture 3: Sockets.
TELE202 Lecture 15 Socket programming 1 Lecturer Dr Z. Huang Overview ¥Last Lecture »TCP/UDP (2) »Source: chapter 17 ¥This Lecture »Socket programming.
University of Calgary – CPSC 441.  A socket is an interface between the application and the network (the lower levels of the protocol stack)  The application.
Introduction to Socket
CSE/EE 461 Getting Started with Networking. 2 Basic Concepts A PROCESS is an executing program somewhere. –Eg, “./a.out” A MESSAGE contains information.
Chapter 27 Socket API Interface The interface between an application program and the communication protocols in an operating system is known as the Application.
Socket Programming Tutorial Department of Computer Science Southern Illinois University Edwardsville Fall, 2015 Dr. Hiroshi Fujinoki
Socket Programming Lab 1 1CS Computer Networks.
1 Sockets Programming Socket to me!. 2 Network Application Programming Interface (API) The services provided by the operating system that provide the.
Socket Programming Introduction. Socket Definition A network socket is one endpoint in a two-way communication flow between two programs running over.
Socket Programming.
S OCKET P ROGRAMMING IN C Professor: Dr. Shu-Ching Chen TA: HsinYu Ha.
S OCKET P ROGRAMMING IN C Professor: Dr. Shu-Ching Chen TA: Hsin-Yu Ha.
Read() recv() connection establishment Server (connection-oriented protocol) blocks until connection from client Client socket() bind() listen() accept()
CSCI 330 UNIX and Network Programming Unit XIV: User Datagram Protocol.
Socket Programming. Computer Science, FSU2 Interprocess Communication Within a single system – Pipes, FIFOs – Message Queues – Semaphores, Shared Memory.
UNIX Sockets Outline UNIX sockets CS 640.
1 Spring Semester 2008, Dept. of Computer Science, Technion Internet Networking recitation #7 Socket Programming.
Lecture 15 Socket Programming CPE 401 / 601 Computer Network Systems slides are modified from Dave Hollinger.
Socket Programming in C CS587x Lecture 3 Department of Computer Science Iowa State University.
1 Socket Interface. 2 Client-Server Architecture The client is the one who speaks first Typical client-server situations  Client and server on the same.
Socket Programming(1/2). Outline  1. Introduction to Network Programming  2. Network Architecture – Client/Server Model  3. TCP Socket Programming.
1 Socket Interface. 2 Basic Sockets API Review Socket Library TCPUDP IP EthernetPPP ARP DHCP, Mail, WWW, TELNET, FTP... Network cardCom Layer 4 / Transport.
Client-Server Model ● Frequently used programming paradigms – client-server model: one process provides services for a set of client process, eg. HTTP.
Jim Fawcett CSE 681 – Software Modeling & Analysis Fall 2002
Jim Fawcett CSE 687-OnLine – Object Oriented Design Summer 2017
Socket Programming in C
Socket Interface 1 Introduction 11 Socket address formats 2 API 12 13
Transport layer API: Socket Programming
UNIX Sockets Outline Homework #1 posted by end of day
Socket Programming in C
28.
Chapter 3 Socket API © Bobby Hoggard, Department of Computer Science, East Carolina University These slides may not be used or duplicated without permission.
Sockets Programming Socket to me!.
Sockets Programming Socket to me!.
Internet Networking recitation #8
Jim Fawcett CSE 681 – Software Modeling & Analysis Summer 2003
Presentation transcript:

1 JMH Associates © 2000, All rights reserved Chapter 12 Windows Sockets and Network Programming

2 JMH Associates © 2000, All rights reserved OBJECTIVESOBJECTIVES Upon completion of this chapter, you will be able to:  Understand the basic Windows Sockets API  Address portability issues between Berkeley and Windows Sockets  Use Windows Sockets over TCP/IP for peer-to-peer and client/server applications  Consider changes introduced by Windows Sockets 2  See how the Service Registration APOI provides protocol transparency

3 JMH Associates © 2000, All rights reserved WINDOWS SOCKETS (1 of 2) An extension of the Berkeley Sockets API  Into the Windows environment Porting of code already written for Berkeley Sockets  Windows stations easily integrated into TCP/IP networks Exceptions when sockets treated as file descriptors  Under UNIX  Also, extended functions with WSA prefix

4 JMH Associates © 2000, All rights reserved WINDOWS SOCKETS (2 of 2) Functions that manipulate files also work with sockets read()ioctl() write()close() Behave like overlapped Windows file handles Other network communication options  Named pipes  Remote Procedure Calls

5 JMH Associates © 2000, All rights reserved INITIALIZE THE WinSock DLL (1 of 2) int WSAStartup( WORD wVersionRequired, LPWSADATA lpWSAData);

6 JMH Associates © 2000, All rights reserved INITIALIZE THE WinSock DLL (2 of 2) wVersionRequired  Indicates the highest version of the WinSock DLL you need  Returns a non-zero value if the DLL cannot support the version you want  Low byte specifies the major version  High byte specifies the minor version  0x0101  version 1.1 lpWSAData points to a WSADATA structure that returns information on the configuration of the DLL WSAGetLastError() for error number

7 JMH Associates © 2000, All rights reserved ALLOCATE A SOCKET (1 of 3) Sockets are analogous to handles  A communication channel Call socket() to create (or open) a socket  Actually a HANDLE

8 JMH Associates © 2000, All rights reserved ALLOCATE A SOCKET (2 of 3)  Server: “Listening socket” for client connection requests typedef unsigned int SOCKET; SOCKET socket(int af, int type, int protocol);

9 JMH Associates © 2000, All rights reserved ALLOCATE A SOCKET (3 of 3)  af denotes the address family  PF_INET or AF_INET designates the Internet protocol  type specifies connection-oriented ( SOCK_STREAM ) or datagram communications ( SOCK_DGRAM )  protocol unnecessary for TCP/IP  Use 0 socket returns INVALID_SOCKET upon failure

10 JMH Associates © 2000, All rights reserved BIND (1 of 3) Next, bind the socket to its address and service endpoint int bind ( SOCKET s, const struct sockaddr *saddr, int namelen);  s is an “unbound” SOCKET returned by socket()  saddr specifies the address family and protocol-specific information  namelen is sizeof(sockaddr) Returns SOCKET_ERROR in case of error

11 JMH Associates © 2000, All rights reserved BIND (2 of 3) SOCKADDR structure struct sockaddr { u_short sa_family; char sa_data[14]; }; typedef struct sockaddr SOCKADDR, *PSPOCKADDR;

12 JMH Associates © 2000, All rights reserved BIND (3 of 3) sa_data is protocol-specific TCP/IP sockaddr_in : struct sockaddr_in { shortsin_family; // AF_INET u_shortsin_port; structin_addr sin_addr; //4-byte IP addr char sinzero [8]; }; typedef struct sockaddr_in SOCKADDR_IN, *PSOCKADDR_IN;

13 JMH Associates © 2000, All rights reserved BIND CONSIDERATIONS List of hosts (mapped to IP addresses) can be found in %SystemRoot%\system32\drivers\etc\hosts List of Services(mapped to services) can be found in %SystemRoot%\system32\drivers\etc\services If you bind to a specific IP address, you can only receive incoming packets over that IP address If you have more than one IP address, bind to hotnl(INADDR_ANY) “host to network long”

14 JMH Associates © 2000, All rights reserved BIND SETUP EXAMPLE (1 of 3) BOOL WINAPI WNetGetHostAddress( LPCSTR lpszHost, LPCSTR lpszService, LPCSTR lpszProto, LPSOCKADDR lpAddr) /* Fill in a SOCKADDR using host, protocol, service */ { LPHOSTENT lpHost; LPSERVENT lpServ; SOCKADDR_IN sin; ZeroMemory(&sin, sizeof(sin));

15 JMH Associates © 2000, All rights reserved BIND SETUP EXAMPLE (2 of 3) sin.sin_family = PF_INET; sin.sin_addr.s_addr = htonl(INADDR_ANY); if(lpszHost != NULL) { lpHost = gethostbyname(lpszHost); if(lpHost != NULL) { CopyMemory(&sin.sin_addr, lpHost->h_addr_list[0], lpHost->h_length); } lpServ = getservbyname(lpszService, lpszProto);

16 JMH Associates © 2000, All rights reserved BIND SETUP EXAMPLE (3 of 3) if(lpServ != NULL) { sin.sin_port = lpServ->s_port; ZeroMemory(sin.sin_zero, sizeof(sin.sin_zero)); CopyMemory(lpAddr, &sin, sizeof(SOCKADDR)); return TRUE; /* lpAddr is now ready for bind() */ } return FALSE; } The address returned by WNetGetHostAddress() can be passed directly to the bind() function

17 JMH Associates © 2000, All rights reserved listen () listen() makes server available for client connection  Socket goes from “bound” to “listening” state int listen(SOCKET s, int nQueueSize); nQueueSize indicates the number of connection requests you are willing to have queued at the socket  Up to SOMAXCON (5 for 1.1, “unlimited” in 2.0)

18 JMH Associates © 2000, All rights reserved accept () (1 of 2)  The call to listen() places the socket into the listening state  The server application calls accept()  Returning a “connected socket”  accept() blocks until a client request for a connection arrives  accept() return value gives the server a new socket for exchanging data

19 JMH Associates © 2000, All rights reserved accept () (2 of 2) SOCKET accept( SOCKET s, /* Listening socket */ LPSOCKADDR lpAddr, /* Find client details here */ LPINT lpnAddrLen /* Length of the returned structure */ );

20 JMH Associates © 2000, All rights reserved THE CLIENT SIDE (1 of 2) A client station wishing to connect to a server must also create a socket by calling socket() If it is not bound by an address, Windows Sockets will assign it a unique address to use for the duration of the connection

21 JMH Associates © 2000, All rights reserved THE CLIENT SIDE (2 of 2) int connect( SOCKET s, LPSOCKADDR lpName, int nNameLen); lpName points to a SOCKADDR structure designating the server machine name and port address

22 JMH Associates © 2000, All rights reserved EXCHANGE OF DATA (1 of 2)  Partner stations exchange data using send() and recv()  send() and recv() have identical arguments: int send (int recv ( SOCKET s, SOCKET s, LPSTR lpBuffer,LPSTR lpBuffer, int nBufferLen,int nBufferLen, int nFlags); int nFlags);

23 JMH Associates © 2000, All rights reserved EXCHANGE OF DATA (2 of 2)  nFlags == MSG_OOB indicates urgency  OOB for out-of-band  MSG_PEEK can be used to peek at the data without removing it  These are standard Berkeley Sockets calls  But read() and write() are more common under UNIX  Not atomic or message oriented  Loop until full message is received  Or sent, although incomplete send() is rare

24 JMH Associates © 2000, All rights reserved DATAGRAM SERVICE (1 of 2) Stations send and receive data using sendto() and recvfrom() Take the same arguments as send() and recv(), but add two to designate the partner station int sendto ( int recvfrom ( SOCKET s, SOCKET s, LPSTR lpBuffer, LPSTR lpBuffer, int nBufferLen, int nBufferLen, int nFlags, int nFlags, LPSOCKADDR lpAddr, LPSOCKADDR lpAddr, int nAddrLen); LPINT pnAddrLen);

25 JMH Associates © 2000, All rights reserved DATAGRAM SERVICE (2 of 2) With datagrams, the nFlags argument cannot be MSG_OOB You cannot send or receive urgent data

26 JMH Associates © 2000, All rights reserved CLOSING A SOCKET  In standard Berkeley Sockets, call close()  In Windows Sockets call void closesocket(SOCKET s);  For connection-oriented communications, the server side of the exchange closes the socket created by accept()  Not the one returned by socket()  Only when the server goes out of service should it close the listening socket  Finally, call void WSACleanup(void);  To break your connection to WSOCK32.DLL  This function is also non-portable

27 JMH Associates © 2000, All rights reserved SOCKETS SUMMARY (1 of 2) Connection Oriented Service ServerClientsocket() bind()connect() listen() accept() send()/recv() sendto()/recvfrom() closesocket()

28 JMH Associates © 2000, All rights reserved SOCKETS SUMMARY (2 of 2) Connectionless (Datagram) ServerClientsocket() listen() connect() send()/recv() sendto()/recvfrom() closesocket()

29 JMH Associates © 2000, All rights reserved BERKELEY vs WINDOWS SOCKETS Standard Berkeley Sockets calls will port to Windows Sockets, with these exceptions:  You must call WSAStartup() to initialize the sockets DLL  Though you can use UNIX-style read() and _write() to receive and send data, you must first convert the Windows socket to an operating system handle by calling _open_osfhandle()  In Sockets 1.1, you also have to call setsockopt() to force sockets to be opened as non-overlapped handles  You must use closesocket() (which is not portable), rather than close() (which is), to close a socket  You must call WSACleanup() to shut down the DLL

30 JMH Associates © 2000, All rights reserved OVERLAPPED I/O WITH WINDOWS SOCKETS (1 of 2) In WinSock 1.1, Windows opens sockets as overlapped file handles You can pass a socket to ReadFile() or WriteFile() without modification  Wait for an operation to complete by tying it to an event handle, and call WaitForSingleObject() WaitForMultipleObjects() or MsgWaitForMultipleObjects

31 JMH Associates © 2000, All rights reserved OVERLAPPED I/O WITH WINDOWS SOCKETS (2 of 2)  Use I/O completion routines with ReadFileEx() / WriteFileEx() and the extended wait functions WaitForSingleObjectEx(), WaitForMultipleObjectsEx(), and SleepEx()  Use an I/O completion port with ReadFile() / WriteFile(), CreateIoCompletionPort(), and GetQueuedCompletionStatus()

32 JMH Associates © 2000, All rights reserved WINDOWS SOCKETS 2 (1 of 2) Windows Sockets 2, available in NT 4.0, adds several areas of functionality Note: Use 1.1 for interoperability reasons  Standardized support for overlapped I/O  Scatter/gather I/O  Sending and receiving from non-contiguous buffers in memory

33 JMH Associates © 2000, All rights reserved WINDOWS SOCKETS 2 (2 of 2)  The ability to request quality of service from the Sockets support layer  Speed and reliability of transmission  The ability to organize sockets into groups  The quality of service of a socket group can be configured  It does not have to be done on a socket-by-socket basis  The sockets belonging to a group can be prioritized  Piggybacking of data onto connection requests  Multipoint connections (conference calls)

34 JMH Associates © 2000, All rights reserved STANDARDIZATION OF OVERLAPPED I/O (1 of 2)  The most important addition to Windows Sockets 2 is the standardization of overlapped I/O  Sockets are no longer created automatically as overlapped file handles  socket() will create a non-overlapped handle  To create an overlapped socket, call WSASocket() and explicitly ask for one

35 JMH Associates © 2000, All rights reserved STANDARDIZATION OF OVERLAPPED I/O (2 of 2) SOCKET WSAAPI WSASocket( int iAddressFamily, int iSocketType, int iProtocol, LPWSAPROTOCOL_INFO lpProtocolInfo, GROUP g, DWORD dwFlags);

36 JMH Associates © 2000, All rights reserved SCATTER/GATHER I/O (1 of 4) WinSock 2 adds the ability to collect and distribute data for transmission or reception from non-contiguous memory buffers typedef struct WSABUF { u_long len; char *buf; }WSABUF, *LPWSABUF;

37 JMH Associates © 2000, All rights reserved SCATTER/GATHER I/O (2 of 4)  buf points to the data  len is the number of bytes in this particular buffer  WSASend(), WSARecv(), WSASendTo(), and WSARecvFrom() take an array of WSABUF structures

38 JMH Associates © 2000, All rights reserved SCATTER/GATHER I/O (3 of 4) int WSARecv( SOCKET s, LPWSABUF lpRecvBuffers, DWORD dwBuffers, LPDWORD lpdwBytesReceived, LPDWORD lpdwFlags, LPWSAOVERLAPPED lpOverlapped, LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine);

39 JMH Associates © 2000, All rights reserved SCATTER/GATHER I/O (4 of 4)  lpRecvBuffers points to an array of WSABUF structures  dwBuffers is the number of structures in the array  When data arrives, the WinSock 2 drivers disperse it among the buffers passed

40 JMH Associates © 2000, All rights reserved LAB B–1 (1 of 2) Use Windows Sockets to connect clients (the client program) to a “command line server”  The clients take a command line and send it to a known server for execution  The server returns the results to the client over the socket The solution consists of two components:  Client.c  Run Client.exe in its own window  Server.c

41 JMH Associates © 2000, All rights reserved LAB B–1 (2 of 2)  Server.c is built as Server.exe and runs in its own window or is controlled with the job management commands from Module 5  Place the commands to be executed in the same directory as Server.exe  The header file, ClntSrvr.h, contains definitions used in the various programs, such as the message format  WSOCK32.LIB must be included when linking Challenge: Extend server to set up service name in services file and client finds it with WNetGetHostAddress