Unit OS A: Windows Networking Unit OS A: Windows Networking
A.3. A.3. Microsoft-specific extensions to Sockets Microsoft-specific extensions to Sockets and other Networking APIs
and other Networking APIs
Copyright Notice Copyright Notice
© 2000-2005 David A. Solomon and Mark Russinovich
© 2000-2005 David A. Solomon and Mark Russinovich
These materials are part of the
These materials are part of the Windows Operating Windows Operating System Internals Curriculum Development Kit,
System Internals Curriculum Development Kit, developed by David A. Solomon and Mark E.
developed by David A. Solomon and Mark E.
Russinovich with Andreas Polze Russinovich with Andreas Polze
Microsoft has licensed these materials from David Microsoft has licensed these materials from David Solomon Expert Seminars, Inc. for distribution to Solomon Expert Seminars, Inc. for distribution to academic organizations solely for use in academic academic organizations solely for use in academic environments (and not for commercial use)
environments (and not for commercial use)
Roadmap for Section A.3 Roadmap for Section A.3
Windows Sockets (winsock2) Extensions Windows Sockets (winsock2) Extensions
Web access APIs Web access APIs
Named pipes and mailslots Named pipes and mailslots
NetBIOS / Wnet API
NetBIOS / Wnet API
Winsock 2.0 Features Winsock 2.0 Features
Windows NT 4.0 was the first operating system with native support Windows NT 4.0 was the first operating system with native support of the Winsock 2.0 specification:
of the Winsock 2.0 specification:
Access to protocols other than TCP/IP, Access to protocols other than TCP/IP, Overlapped I/O,
Overlapped I/O,
Ability to query and request specific qualities of service Ability to query and request specific qualities of service
New header file and libraries:
New header file and libraries:
WS2_32.LIB / WS2_32.DLL WS2_32.LIB / WS2_32.DLL winsock2.h
winsock2.h
Microsoft extensions to Winsock have been moved out into their Microsoft extensions to Winsock have been moved out into their own separate DLL
own separate DLL
WINSOCK.DLL contains forwarders to these routines WINSOCK.DLL contains forwarders to these routines
Microsoft-specific Extensions Microsoft-specific Extensions
to Berkeley Sockets to Berkeley Sockets
Tailored to the message-passing environment of Tailored to the message-passing environment of windows
windows WSA –
WSA – Windows Sockets Asynchronous Windows Sockets Asynchronous prefix prefix Roots in Windows 3.1
Roots in Windows 3.1
Windows Sockets Committee Windows Sockets Committee
# include <winsock.h>
# include <winsock.h>
Request event notification for a Request event notification for a
socket socket
Request a message to the window hWnd whenever any of the network Request a message to the window hWnd whenever any of the network events specified by the lEvent occurs
events specified by the lEvent occurs. .
Message which should be sent is specified by the wMsg parameter.
Message which should be sent is specified by the wMsg parameter.
The socket for which notification is required is identified by s The socket for which notification is required is identified by s
int PASCAL FAR WSAAsyncSelect ( SOCKET s, HWND hWnd,
unsigned int wMsg, long lEvent );
Value
Value MeaningMeaning FD_READ
FD_READ Want to receive notification of readiness for reading Want to receive notification of readiness for reading FD_WRITE
FD_WRITE Want to receive notification of readiness for writing Want to receive notification of readiness for writing FD_OOB
FD_OOB Want to receive notification of the arrival of out-of-band data Want to receive notification of the arrival of out-of-band data FD_ACCEPT
FD_ACCEPT Want to receive notification of incoming connections Want to receive notification of incoming connections FD_CONNECT
FD_CONNECT Want to receive notification of completed connection Want to receive notification of completed connection
WSAAsyncSelect (contd.) WSAAsyncSelect (contd.)
Every window must have a window procedure Every window must have a window procedure
Arguments to window procedure for notification window:
Arguments to window procedure for notification window:
wParam contains socket number wParam contains socket number
lParam contains event code and any error that may have occured lParam contains event code and any error that may have occured Event status:
Event status:
LRESULT WINAPI WndProc( HWND hWnd,
UINT msg, WPARAM wParam, LPARAM lParam);
switch( msg ) {
case WM_PAINT: ...
case WM_DESTROY: ...
case FD_ACCEPT: ...
default: return( DefWindowProc( hWnd, msg, wParam, lParam ));
}
WSAAsynchSelect (contd.) WSAAsynchSelect (contd.)
Report the event:
Report the event:
WORD wEvent = WSAGETSELECTEVENT( lParam );
WORD wEvent = WSAGETSELECTEVENT( lParam );
Enabling functions reactivate WSAAsyncSelect:
Enabling functions reactivate WSAAsyncSelect:
For FD_READ, FD_OOB events:
For FD_READ, FD_OOB events:
ReadFile(), read(), recv(), recvfrom() are enabling functions ReadFile(), read(), recv(), recvfrom() are enabling functions For FD_WRITE events:
For FD_WRITE events:
WriteFile(), write(), send(), sendto() are enabling functions WriteFile(), write(), send(), sendto() are enabling functions
Request notification of different events:
Request notification of different events:
Call WSAAsyncSelect() again Call WSAAsyncSelect() again
WSAAsyncSelect (contd.) WSAAsyncSelect (contd.)
Issuing a WSAAsyncSelect() for a socket cancels any previous Issuing a WSAAsyncSelect() for a socket cancels any previous WSAAsyncSelect() for the same socket.
WSAAsyncSelect() for the same socket.
For example, to receive notification for both reading and writing, the For example, to receive notification for both reading and writing, the application must call WSAAsyncSelect() with both FD_READ and application must call WSAAsyncSelect() with both FD_READ and FD_WRITE, as follows:
FD_WRITE, as follows:
rc = WSAAsyncSelect(s, hWnd, wMsg, FD_READ | FD_WRITE);
rc = WSAAsyncSelect(s, hWnd, wMsg, FD_READ | FD_WRITE);
It is not possible to specify different messages for different events.
It is not possible to specify different messages for different events.
The following code will not work; the second call will cancel the effects of the The following code will not work; the second call will cancel the effects of the first, and only FD_WRITE events will be reported with message wMsg2:
first, and only FD_WRITE events will be reported with message wMsg2:
rc = WSAAsyncSelect(s, hWnd, wMsg1, FD_READ);
rc = WSAAsyncSelect(s, hWnd, wMsg1, FD_READ);
rc = WSAAsyncSelect(s, hWnd, wMsg2, FD_WRITE);
rc = WSAAsyncSelect(s, hWnd, wMsg2, FD_WRITE);
To cancel all notification - i.e., to indicate that the Windows Sockets To cancel all notification - i.e., to indicate that the Windows Sockets
implementation should send no further messages related to network events on implementation should send no further messages related to network events on the socket - lEvent should be set to zero.
the socket - lEvent should be set to zero.
Use of WSAAsyncSelect Use of WSAAsyncSelect
- Server Side - Server Side
1.1. Create a socket and bind your address to itCreate a socket and bind your address to it
2.2. Call WSAAsyncSelect():Call WSAAsyncSelect():
Request FD_ACCEPT notification Request FD_ACCEPT notification
3.3. Call listen() – returns immediatelyCall listen() – returns immediately
4.4. When connection request comes in:When connection request comes in:
Notification window receives FD_ACCEPT notification Notification window receives FD_ACCEPT notification Respond by calling accept()
Respond by calling accept()
5.5. Call WSAAsyncSelect():Call WSAAsyncSelect():
Request FD_READ | FD_OOB | FD_CLOSE notifications for socket Request FD_READ | FD_OOB | FD_CLOSE notifications for socket returned by accept()
returned by accept()
6.6. Receiving FD_READ, FD_OOB notifications:Receiving FD_READ, FD_OOB notifications:
Call ReadFile(), read(), recv(), recvfrom() to retrieve the data Call ReadFile(), read(), recv(), recvfrom() to retrieve the data
7.7. Respond to FD_CLOSE notification by calling closesocket()Respond to FD_CLOSE notification by calling closesocket()
Use of WSAAsyncSelect() Use of WSAAsyncSelect()
- Client Side - Client Side
1. 1. Create a socket Create a socket
2. 2. Call WSAAsyncSelect(): Call WSAAsyncSelect():
Request FD_CONNECT notification Request FD_CONNECT notification
3. 3. Call connect() – returns immediately Call connect() – returns immediately
4. 4. When FD_CONNECT notification comes in: When FD_CONNECT notification comes in:
Request FD_READ | FD_OOB | FD_CLOSE notification on socket Request FD_READ | FD_OOB | FD_CLOSE notification on socket (reported in wParam)
(reported in wParam)
5. 5. When data from the server arrives: When data from the server arrives:
Notification window receives FD_READ or FD_OOB events Notification window receives FD_READ or FD_OOB events Respond by calling ReadFile(), read(), recv(), or recvfrom() Respond by calling ReadFile(), read(), recv(), or recvfrom() Client should be prepared for FD_CLOSE notification
Client should be prepared for FD_CLOSE notification
Get host information corresponding Get host information corresponding
to an address - asynchronous to an address - asynchronous
version version
type:
type:
The type of the address, which must be The type of the address, which must be PF_INET.
PF_INET.
buf:
buf:
A pointer to the data area to receive the A pointer to the data area to receive the hostent data. Note that this must be larger hostent data. Note that this must be larger than the size of a hostent structure. It is than the size of a hostent structure. It is recommended that you supply a buffer of recommended that you supply a buffer of MAXGETHOSTSTRUCT bytes.
MAXGETHOSTSTRUCT bytes.
buflen:
buflen:
The size of data area buf above.
The size of data area buf above.
• hWnd:
– The handle of the window which should receive a message when the asynchronous request completes.
• wMsg:
– The message to be received when the asynchronous request completes.
• addr:
– A pointer to the network address for the host. Host addresses are stored in network byte order.
• len:
– The length of the address, which must be 4 for PF_INET.
HANDLE PASCAL FAR WSAAsyncGetHostByAddr ( HWND hWnd, unsigned int wMsg,
const char FAR * addr, int len, int type, char FAR * buf, int buflen );
asynchronous version of gethostbyaddr()
WSAAsyncGetHostByAddr (contd.) WSAAsyncGetHostByAddr (contd.)
When the asynchronous operation is complete the application's When the asynchronous operation is complete the application's
window hWnd receives message wMsg.
window hWnd receives message wMsg.
The wParam argument contains the asynchronous task handle as The wParam argument contains the asynchronous task handle as
returned by the original function call.
returned by the original function call.
The high 16 bits of lParam contain any error code.
The high 16 bits of lParam contain any error code.
The error code may be any error as defined in winsock.h.
The error code may be any error as defined in winsock.h.
An error code of zero indicates successful completion of the An error code of zero indicates successful completion of the
asynchronous operation.
asynchronous operation.
On successful completion, the buffer supplied to the original function On successful completion, the buffer supplied to the original function
call contains a hostent structure.
call contains a hostent structure.
To access the elements of this structure, the original buffer address To access the elements of this structure, the original buffer address
should be cast to a hostent structure pointer and accessed as should be cast to a hostent structure pointer and accessed as
appropriate.
appropriate.
Get host information corresponding Get host information corresponding
to a hostname - asynchronous to a hostname - asynchronous
version version
hWnd:
hWnd:
The handle of the window which should receive a message when the The handle of the window which should receive a message when the asynchronous request completes.
asynchronous request completes.
wMsg:
wMsg:
The message to be received when the asynchronous request completes.
The message to be received when the asynchronous request completes.
Name:
Name:
A pointer to the name of the host.
A pointer to the name of the host.
Buf:Buf:
A pointer to the data area to receive the hostent data. It is recommended that you A pointer to the data area to receive the hostent data. It is recommended that you supply a buffer of MAXGETHOSTSTRUCT bytes.
supply a buffer of MAXGETHOSTSTRUCT bytes.
Buflen:
Buflen:
The size of data area buf above.
The size of data area buf above.
HANDLE PASCAL FAR WSAAsyncGetHostByName ( HWND hWnd, unsigned int wMsg,
const char FAR * name, char FAR * buf, int buflen );
asynchronous version of gethostbyname()
Get protocol information corresponding Get protocol information corresponding
to a protocol name - asynchronous to a protocol name - asynchronous
version version
hWnd hWnd
The handle of the window which should receive a message when the The handle of the window which should receive a message when the asynchronous request completes.
asynchronous request completes.
wMsg wMsg
The message to be received when the asynchronous request completes.
The message to be received when the asynchronous request completes.
name name
A pointer to the protocol name to be resolved.
A pointer to the protocol name to be resolved.
buf buf
A pointer to the data area to receive the protoent data. (supply a buffer of A pointer to the data area to receive the protoent data. (supply a buffer of MAXGETHOSTSTRUCT bytes)
MAXGETHOSTSTRUCT bytes)
HANDLE PASCAL FAR WSAAsyncGetProtoByName ( HWND hWnd, unsigned int wMsg,
const char FAR * name, char FAR * buf, int buflen );
asynchronous version of getprotobyname()
Get protocol information corresponding Get protocol information corresponding
to a protocol number - asynchronous to a protocol number - asynchronous
version version
hWnd hWnd
The handle of the window which should receive a message when the The handle of the window which should receive a message when the asynchronous request completes.
asynchronous request completes.
wMsg wMsg
The message to be received when the asynchronous request completes.
The message to be received when the asynchronous request completes.
number number
The protocol number to be resolved, The protocol number to be resolved, in host byte order.
in host byte order.
buf buf
A pointer to the data area to receive the protoent data (supply a buffer of A pointer to the data area to receive the protoent data (supply a buffer of MAXGETHOSTSTRUCT bytes)
MAXGETHOSTSTRUCT bytes) buflen
buflen
The size of data area buf above.
The size of data area buf above.
HANDLE PASCAL FAR WSAAsyncGetProtoByNumber ( HWND hWnd, unsigned int wMsg,
int number, char FAR * buf, int buflen );
asynchronous version of getprotobynumber()
Additional Asynchronous Additional Asynchronous
Socket Routines Socket Routines
WSAAsyncGetServByName() WSAAsyncGetServByName() WSAAsyncGetServByPort() WSAAsyncGetServByPort() WSACancelAsyncRequest() WSACancelAsyncRequest() WSACancelBlockingCall() WSACancelBlockingCall() WSACleanup()
WSACleanup()
WSAGetLastError() WSAGetLastError() WSAIsBlocking() WSAIsBlocking()
WSASetBlockingHook(), WSAUnhookBlockingHook() WSASetBlockingHook(), WSAUnhookBlockingHook() WSASetLastError()
WSASetLastError() WSAStartup()
WSAStartup()
WSASetBlockingHook WSASetBlockingHook
Application invokes a blocking Sockets operation:
Application invokes a blocking Sockets operation:
the Windows Sockets implementation initiates the operation and then the Windows Sockets implementation initiates the operation and then
enters a loop which is similar to the following pseudocode:
enters a loop which is similar to the following pseudocode:
for(;;) { for(;;) {
/* flush messages for good user response */
/* flush messages for good user response */
while(BlockingHook()) ; while(BlockingHook()) ;
/* check for WSACancelBlockingCall() */
/* check for WSACancelBlockingCall() */
if(operation_cancelled()) break;
if(operation_cancelled()) break;
/* check to see if operation completed */
/* check to see if operation completed */
if(operation_complete()) break;
if(operation_complete()) break;
/* normal completion */
/* normal completion */
}}
support those applications which require more complex message processing –
MDI (multiple document
Web API: Internet Support Web API: Internet Support
WININET.DLL supports HTTP, FTP, Gopher protocols WININET.DLL supports HTTP, FTP, Gopher protocols General-purpose WinInet Functions
General-purpose WinInet Functions
InternetOpen InternetOpen
InternetConnect InternetConnect InternetOpenUrl InternetOpenUrl InternetReadFile InternetReadFile
InternetCloseHandle InternetCloseHandle
InternetSetStatusCallback InternetSetStatusCallback
InternetQueryOption InternetQueryOption
InternetSetOption
InternetSetOption
Internet Suport Internet Suport
(http/gopher protocols) (http/gopher protocols)
WinInet HTTP Functions WinInet HTTP Functions
HttpOpenRequest HttpOpenRequest
HttpAddRequestHeaders HttpAddRequestHeaders HttpSendRequest
HttpSendRequest HttpQueryInfo HttpQueryInfo
WinInet Gopher Functions WinInet Gopher Functions
GopherFindFirstFile GopherFindFirstFile GopherOpenFile GopherOpenFile
GopherCreateLocator GopherCreateLocator GopherGetAttribute GopherGetAttribute
Internet Support (ftp protocol) Internet Support (ftp protocol)
WinInet FTP Functions WinInet FTP Functions
FtpFindFirstFile FtpFindFirstFile
FtpGetFile FtpGetFile FtpPutFile FtpPutFile
FtpDeleteFile FtpDeleteFile
FtpRenameFile FtpRenameFile
FtpOpenFile FtpOpenFile
InternetWriteFile InternetWriteFile
FtpCreateDirectory FtpCreateDirectory
FtpRemoveDirectory FtpRemoveDirectory
FtpSetCurrentDirectory FtpSetCurrentDirectory FtpGetCurrentDirectory FtpGetCurrentDirectory
FtpCommand FtpCommand
InternetGetLastResponseInfo InternetGetLastResponseInfo
Most of the WinInet functions work with
or return HINTERNETs (handles to Internet).
While your code sees all HINTERNETs as the same type, one HINTERNET can mean
something completely different from another.
The first type of HINTERNET that you obtain comes when you initialize
WININET.DLL by calling InternetOpen.
This is the first of 13 possible subtypes of HINTERNETs.
HINTERNET subtypes HINTERNET subtypes
Query the subtype of Query the subtype of a particular handle a particular handle by calling:
by calling:
InternetQuery InternetQuery Option
Option
and sending it the and sending it the HINTERNET with the HINTERNET with the INTERNET_OPTION_H INTERNET_OPTION_H ANDLE_TYPE
ANDLE_TYPE parameter parameter
INTERNET_HANDLE_TYPE_INTERNET
INTERNET_HANDLE_TYPE_INTERNET 11 INTERNET_HANDLE_TYPE_CONNECT_FTP
INTERNET_HANDLE_TYPE_CONNECT_FTP 22 INTERNET_HANDLE_TYPE_CONNECT_GOPHER
INTERNET_HANDLE_TYPE_CONNECT_GOPHER 33 INTERNET_HANDLE_TYPE_CONNECT_HTTP
INTERNET_HANDLE_TYPE_CONNECT_HTTP 44 INTERNET_HANDLE_TYPE_FTP_FIND
INTERNET_HANDLE_TYPE_FTP_FIND 55 INTERNET_HANDLE_TYPE_FTP_FIND_HTML
INTERNET_HANDLE_TYPE_FTP_FIND_HTML 66 INTERNET_HANDLE_TYPE_FTP_FILE
INTERNET_HANDLE_TYPE_FTP_FILE 77 INTERNET_HANDLE_TYPE_FTP_FILE_HTML
INTERNET_HANDLE_TYPE_FTP_FILE_HTML 88 INTERNET_HANDLE_TYPE_GOPHER_FIND
INTERNET_HANDLE_TYPE_GOPHER_FIND 99 INTERNET_HANDLE_TYPE_GOPHER_FIND_HTML
INTERNET_HANDLE_TYPE_GOPHER_FIND_HTML 1010 INTERNET_HANDLE_TYPE_GOPHER_FILE
INTERNET_HANDLE_TYPE_GOPHER_FILE 1111 INTERNET_HANDLE_TYPE_GOPHER_FILE_HTML
INTERNET_HANDLE_TYPE_GOPHER_FILE_HTML 1212 INTERNET_HANDLE_TYPE_HTTP_REQUEST
INTERNET_HANDLE_TYPE_HTTP_REQUEST 1313
Windows HTTP Services
Windows HTTP Services (WinHTTP) (WinHTTP)
HTTP client API to send requests through the HTTP HTTP client API to send requests through the HTTP protocol to other HTTP servers
protocol to other HTTP servers
WinHTTP supports desktop client applications, Windows WinHTTP supports desktop client applications, Windows
services, and Windows server-based applications services, and Windows server-based applications
WinHTTP offers both a C/C++ application programming WinHTTP offers both a C/C++ application programming
interface (API) and a COM automation component use in interface (API) and a COM automation component use in
Active Server Pages Active Server Pages
WinHTTP 5.1 is an OS component of:
WinHTTP 5.1 is an OS component of:
Windows Server 2003 family Windows Server 2003 family
Windows XP SP1 Windows XP SP1
Windows 2000 SP3 (except Datacenter Server)
Windows 2000 SP3 (except Datacenter Server)
Usage of the WinHTTP API Usage of the WinHTTP API
Windows HTTP API exposes a set of C/C++ functions that enable Windows HTTP API exposes a set of C/C++ functions that enable applications to access HTTP resources on the Web
applications to access HTTP resources on the Web
Using Internet Functions Using Internet Functions
After setting up WININET.DLL, the initial HINTERNET is usually passed to After setting up WININET.DLL, the initial HINTERNET is usually passed to InternetConnect,
InternetConnect,
parameter indicates the type of connecting server (HTTP, FTP, or parameter indicates the type of connecting server (HTTP, FTP, or Gopher).
Gopher).
InternetConnect returns another subtype of HINTERNET, which is then InternetConnect returns another subtype of HINTERNET, which is then passed to the appropriate HTTP, FTP, or Gopher functions.
passed to the appropriate HTTP, FTP, or Gopher functions.
Alternatively call InternetOpenUrl (parses the URL; connects to the Alternatively call InternetOpenUrl (parses the URL; connects to the appropriate type of server automatically)
appropriate type of server automatically) After connecting to the desired server:
After connecting to the desired server:
turn to the protocol-specific functions turn to the protocol-specific functions
read data from the server via InternetReadFile (works with read data from the server via InternetReadFile (works with HINTERNETs for any of the three supported protocols) HINTERNETs for any of the three supported protocols) Before exiting the program:
Before exiting the program:
all of the HINTERNETs should be closed by calling all of the HINTERNETs should be closed by calling InternetCloseHandle.
InternetCloseHandle.
Named Pipes Named Pipes
Message oriented:
Message oriented:
Reading process can read varying-length messages precisely as Reading process can read varying-length messages precisely as sent by the writing process
sent by the writing process
Bi-directional Bi-directional
Two processes can exchange messages over the same pipe Two processes can exchange messages over the same pipe
Multiple, independent instances of a named pipe:
Multiple, independent instances of a named pipe:
Several clients can communicate with a single server Several clients can communicate with a single server using the same instance
using the same instance
Server can respond to client using the same instance Server can respond to client using the same instance
Pipe can be accessed over the network Pipe can be accessed over the network
location transparency location transparency
Convenience and connection functions
Convenience and connection functions
Using Named Pipes Using Named Pipes
lpszPipeName:
lpszPipeName: \\.\pipe\[\\.\pipe\[path]pipenamepath]pipename
Not possible to create a pipe on remote machine (. – local machine) Not possible to create a pipe on remote machine (. – local machine) fdwOpenMode:
fdwOpenMode:
PIPE_ACCESS_DUPLEX, PIPE_ACCESS_INBOUND, PIPE_ACCESS_DUPLEX, PIPE_ACCESS_INBOUND, PIPE_ACCESS_OUTBOUND
PIPE_ACCESS_OUTBOUND fdwPipeMode:
fdwPipeMode:
PIPE_TYPE_BYTE or PIPE_TYPE_MESSAGE PIPE_TYPE_BYTE or PIPE_TYPE_MESSAGE
PIPE_READMODE_BYTE or PIPE_READMODE_MESSAGE PIPE_READMODE_BYTE or PIPE_READMODE_MESSAGE PIPE_WAIT or PIPE_NOWAIT (will ReadFile block?)
PIPE_WAIT or PIPE_NOWAIT (will ReadFile block?)
HANDLE CreateNamedPipe (LPCTSTR lpszPipeName, DWORD fdwOpenMode, DWORD fdwPipMode DWORD nMaxInstances, DWORD cbOutBuf, DWORD cbInBuf, DWORD dwTimeOut,
LPSECURITY_ATTRIBUTES lpsa );
Use same flag settings for all instances of a named pipe
Named Pipes (contd.) Named Pipes (contd.)
nMaxInstances:
nMaxInstances:
Number of instances, Number of instances,
PIPE_UNLIMITED_INSTANCES: OS choice based on resources PIPE_UNLIMITED_INSTANCES: OS choice based on resources dwTimeOut
dwTimeOut
Default time-out period (in msec) for WaitNamedPipe() Default time-out period (in msec) for WaitNamedPipe() First CreateNamedPipe creates named pipe
First CreateNamedPipe creates named pipe
Closing handle to last instance deletes named pipe Closing handle to last instance deletes named pipe Polling a pipe:
Polling a pipe:
Nondestructive – is there a message waiting for ReadFile Nondestructive – is there a message waiting for ReadFile
BOOL PeekNamedPipe (HANDLE hPipe,
LPVOID lpvBuffer, DWORD cbBuffer,
LPDWORD lpcbRead, LPDWORD lpcbAvail, LPDWORD lpcbMessage);
Named Pipe Client Connections Named Pipe Client Connections
CreateFile with named pipe name:
CreateFile with named pipe name:
\\.\pipe\[
\\.\pipe\[path]pipenamepath]pipename
\\\\servername\pipe\[path]pipenameservername\pipe\[path]pipename
First method gives better performance (local server) First method gives better performance (local server)
Status Functions:
Status Functions:
GetNamedPipeHandleState GetNamedPipeHandleState SetNamedPipeHandleState SetNamedPipeHandleState GetNamedPipeInfo
GetNamedPipeInfo
Convenience Functions Convenience Functions
WriteFile / ReadFile sequence:
WriteFile / ReadFile sequence:
BOOL TransactNamedPipe( HANDLE hNamedPipe, LPVOID lpvWriteBuf, DWORD cbWriteBuf, LPVOID lpvReadBuf, DWORD cbReadBuf, LPDOWRD lpcbRead, LPOVERLAPPED lpa);
• CreateFile / WriteFile / ReadFile / CloseHandle:
- dwTimeOut: NMPWAIT_NOWAIT, NMPWAIT_WIAT_FOREVER, NMPWAIT_USE_DEFAULT_WAIT
BOOL CallNamedPipe( LPCTSTR lpszPipeName, LPVOID lpvWriteBuf, DWORD cbWriteBuf, LPVOID lpvReadBuf, DWORD cbReadBuf, LPDWORD lpcbRead, DWORD dwTimeOut);
Server: eliminate the polling loop Server: eliminate the polling loop
lpo == NULL:
lpo == NULL:
Call will return as soon as there is a client connection Call will return as soon as there is a client connection
Returns false if client connected between CreateNamed Pipe call Returns false if client connected between CreateNamed Pipe call and ConnectNamedPipe()
and ConnectNamedPipe()
Use DisconnectNamedPipe to free the handle for connection from another Use DisconnectNamedPipe to free the handle for connection from another client
client
WaitNamedPipe():
WaitNamedPipe():
Client may wait for server‘s ConnectNamedPipe() Client may wait for server‘s ConnectNamedPipe()
Security rights for named pipes:
Security rights for named pipes:
GENERIC_READ, GENERIC_WRITE, SYNCHRONIZE GENERIC_READ, GENERIC_WRITE, SYNCHRONIZE
BOOL ConnectNamedPipe (HANDLE hNamedPipe, LPOVERLAPPED lpo );
Windows IPC - Mailslots Windows IPC - Mailslots
Broadcast mechanism:
Broadcast mechanism:
One-directional One-directional
Mutliple writers/multiple readers (frequently: one-to-many comm.) Mutliple writers/multiple readers (frequently: one-to-many comm.) Message delivery is unreliable
Message delivery is unreliable
Can be located over a network domain Can be located over a network domain
Message lengths are limited (w2k: < 426 byte) Message lengths are limited (w2k: < 426 byte) Operations on the mailslot:
Operations on the mailslot:
Each reader (server) creates mailslot with CreateMailslot() Each reader (server) creates mailslot with CreateMailslot() Write-only client opens mailslot with CreateFile() and
Write-only client opens mailslot with CreateFile() and
uses WriteFile() – open will fail if there are no waiting readers uses WriteFile() – open will fail if there are no waiting readers Client‘s message can be read by all servers (readers)
Client‘s message can be read by all servers (readers) Client lookup:
Client lookup: \\*\mailslot\mailslotname\\*\mailslot\mailslotname
Client will connect to every server in network domain Client will connect to every server in network domain
Mailslots bear some nasty implementation details;
they are almost never used
Locate a server via mailslot Locate a server via mailslot
hMS = CreateMailslot(
“\\.\mailslot\status“);
ReadFile(hMS, &ServStat);
/* connect to server */
hMS = CreateMailslot(
“\\.\mailslot\status“);
ReadFile(hMS, &ServStat);
/* connect to server */
App client 0
App client n
Mailslot Servers
While (...) { Sleep(...);
hMS = CreateFile(
“\\.\mailslot\status“);
...
WriteFile(hMS, &StatInfo }
App Server
Mailslot Client
Message is sent periodically
Creating a mailslot Creating a mailslot
lpszName points to a name of the form lpszName points to a name of the form
\\.\mailslot\[path]name
\\.\mailslot\[path]name
Name must be unique; mailslot is created locally Name must be unique; mailslot is created locally
cbMaxMsg is msg size in byte cbMaxMsg is msg size in byte dwReadTimeout
dwReadTimeout
Read operation will wait for so many msec Read operation will wait for so many msec 0 – immediate return
0 – immediate return
MAILSLOT_WAIT_FOREVER – infinite wait MAILSLOT_WAIT_FOREVER – infinite wait
HANDLE CreateMailslot(LPCTSTR lpszName, DWORD cbMaxMsg,
DWORD dwReadTimeout,
LPSECURITY_ATTRIBUTES lpsa);
Opening a mailslot Opening a mailslot
CreateFile with the following names:
CreateFile with the following names:
\\.\mailslot\[path]name
\\.\mailslot\[path]name - retrieve handle for local mailslot - retrieve handle for local mailslot
\\host\mailslot\[path]name
\\host\mailslot\[path]name - retrieve handle - retrieve handle for mailslot on specified host
for mailslot on specified host
\\domain\mailslot\[path]name
\\domain\mailslot\[path]name - returns handle representing all - returns handle representing all mailslots on machines in the domain
mailslots on machines in the domain
\\*\mailslot\[path]name
\\*\mailslot\[path]name - returns handle representing mailslots on - returns handle representing mailslots on machines in the system‘s primary domain: max mesg. len: 400 bytes machines in the system‘s primary domain: max mesg. len: 400 bytes Client must specifiy FILE_SHARE_READ flag
Client must specifiy FILE_SHARE_READ flag
GetMailslotInfo() and SetMailslotInfo() are similar to their named GetMailslotInfo() and SetMailslotInfo() are similar to their named pipe counterparts
pipe counterparts
W W N N et API et API
Connection Functions Connection Functions
WNetAddConnection WNetAddConnection WNetAddConnection2 WNetAddConnection2 WNetAddConnection3 WNetAddConnection3 WNetCancelConnection WNetCancelConnection WNetCancelConnection2 WNetCancelConnection2 WNetConnectionDialog WNetConnectionDialog WNetConnectionDialog1 WNetConnectionDialog1 WNetDisconnectDialog WNetDisconnectDialog WNetDisconnectDialog1 WNetDisconnectDialog1 WNetGetConnection WNetGetConnection WNetGetUniversalName WNetGetUniversalName
• Enumeration Functions
– WNetCloseEnum – WNetEnumResource – WNetOpenEnum
• Information Functions
– WNetGetNetworkInformation – WNetGetLastError
– WNetGetProviderName
– WNetGetResourceInformation – WNetGetResourceParent
• User Functions
– WNetGetUser
WNetAddConnection WNetAddConnection
connect a local device to a network resource connect a local device to a network resource successful connection is persistent
successful connection is persistent
system automatically restores the connection during subsequent logon operations system automatically restores the connection during subsequent logon operations lpRemoteName
lpRemoteName
Points to a null-terminated string that specifies the network resource to connect to.
Points to a null-terminated string that specifies the network resource to connect to.
lpPassword lpPassword
Points to a null-terminated string that specifies the password to be used to make a connection. This Points to a null-terminated string that specifies the password to be used to make a connection. This parameter is usually the password associated with the current user.
parameter is usually the password associated with the current user.
NULL: the default password is used. If the string is empty, no password is used.
NULL: the default password is used. If the string is empty, no password is used.
lpLocalName lpLocalName
Points to a null-terminated string that specifies the name of a local device to be redirected, such as F:
Points to a null-terminated string that specifies the name of a local device to be redirected, such as F:
or LPT1. The case of the characters in the string is not important.
or LPT1. The case of the characters in the string is not important.
DWORD WNetAddConnection(
LPTSTR lpRemoteName, // pointer to network device name LPTSTR lpPassword, // pointer to password
LPTSTR lpLocalName // pointer to local device name );
WNetGetConnection WNetGetConnection
retrieves the name of the network resource associated with a local device.
retrieves the name of the network resource associated with a local device.
DWORD WNetGetConnection(
LPCTSTR lpLocalName, // pointer to local name
LPTSTR lpRemoteName, // pointer to buffer for remote name LPDWORD lpnLength // pointer to buffer size, in characters );
• lpLocalName
• Points to a null-terminated string that specifies the name of the local device to get the network name for.
• lpRemoteName
• Points to a buffer that receives the null-terminated remote name
• lpnLength
• Points to a variable that specifies the size´of the buffer.