Lin Jun
The author has introduced the application provided by the major Winsock 1.1 in the previous sect of the article.
Exhibition; I also believe that readers have begun to use these APIs to develop their own network applications.
. But may still have some readers or unclear what kind of development tools can be developed first.
WINSOCK 1.1 application?
Basically, the reader of course must have a compilation program such as Microsoft C or Borland C.
(Compiler) can compile your program; only two of the files related to Winsock, one
Is "Winsock.h" and the other is "Winsock.lib". These two files, readers can use
Anonymous ftp's way from SEEDNET Taipei host "tps1.seed.net.tw"
The "UPLOAD / WINKING / WINSOCK_DOCUMENTS" directory is obtained.
Then I will introduce the remaining various functions for you, including Select (), setsockopt (),
GetSockopt (), and change the system's blocking hook card, what you want to use
WsaseTBlockingHook () and WSAUNHOKBLOCKINGHOK ().
[Special SELECT Funny]
If you have written the UNIX BSD Socket program, you must know this select ().
It is easy to use. Because it can help you check if you can read, write information, and write information.
Can be used to check if the socket has been successfully connected to the other party, or whether the other party has been opposed
Socket is closed, and so on.
But in the environment of Winsock 1.1 and MS Windows 3.x "non-mandatory multi-workers", it is
Still still so easy? When we use it, do you pay attention to what? Let the author come now
Tell you.
◎ SELECT (): Check if one or more sockets are readable, writable, or erroneous.
Format: Int Pascal Far Select (int NFDS, FD_SET FAR * READFDS,
FD_SET FAR * WRITEFDS, FD_SET FAR * EXCEPTFDS, Const Struct Timeval FAR
* Timeout
Parameters: NFDS This parameter has no effect here.
Readfds To be checked, Sockets
Writefds wants to be checked for Sockets
Exceptfds is to be checked if there is a wrong sockets
Timeout This letter should wait for time
Passage: Success - the total number of Sockets eligible (0 is 0 if Timeout occurs)
Failure - Socket_ERROR (Call WsageTlasterror () can know the reason)
Explanation: Users can use this file to check if Sockets can be read,
Or there is a space that can be written, or there is an error.
Winsock 1.1 provided SELECT () Veric with Unix BSD's SELECT () in the parameter
The same as the data type is the same, all have NFDS, Readfds, Writefds, ExceptFDs, and Timeout
Five parameters; but Winsock's NFDS is no effect, with this parameter purpose, just for
Unanimously consistent with the SELECT () letter of UNIX BSD.
As for ReadFDs, WriteFDs, ExceptFDs is also a collection of sockets, so you can
At the same time, the number of many sockets is set in these three parameters; of course, these Sockets must be established by your application. If you have any one of the Socket number you set, you don't belong to you.
This approach, the call select () is failed (error code is 10038)
WSAENOTSOCK.
Winsock also provides some macros to make you set or check readfds, writefds,
The value of ExceptFDs, including: (where s is representative, the number of Socket, the set represented
Is Readfds, WriteFDS or ExcePTFDSs
FD_ZERO (* SET) - clean the value of the set
FD_SET (S, * SET) - Add S to SET
FD_CLR (S, * SET) - Remove S from SET
FD_ISSET (S, * SET) - Check if S is existed in SET
Readers must know the parameters readfds, Writefds, and ExcePTFDS are "Called by Value-
Result ";" Called By Value-Result "means that we are passing the parameters to the system
When you set the start value first, and the address of these parameters is told the system;
These values are used to do some operations or other purposes, and finally and write the results back to the location of these parameters.
Therefore, the values of these parameters may be different after incorporation, and they may be different; so the readers receive each time
Before SELECT (), these parameters must reset their values.
Suppose we have to check if Socket 1 and 2 can be used to transmit information, and Socket 3 is
No information is readable; we don't plan to check if there is an error in Sockets, so ExceptFDS is set to
NULL. The step is approximately as follows:
FD_ZERO (& WriteFDs); / * Clear WriteFDS * /
FD_ZERO (& READFDS); / * Clear ReadFDS * /
FD_SET (1, & Writefds); / * Add Socket 1 to WriteFDS * /
FD_SET (2, & Writefds); / * Add Socket 2 to WriteFDS * /
Fd_set (3, & readfds); / * Add Socket 3 to ReadFDS * /
Select (..., & readfds, & writefds, null, ...) / * Call SELECT () to check events * /
IF (fd_isset (1, & writefds)) / * Check if Socket 1 can be written * /
Send (1, DATA); / * Call send () must be successful * /
IF (fd_isset (2, & writefds)) / * Check if Socket 2 can be written * /
Send (2, DATA); / * Call send () must be successful * /
IF (fd_isset (3, & readfds)) / * Check if Socket 2 is readable * /
RECV (3, DATA); / * Call RECV () must be successful * /
The fifth parameter "Timeout" of the select () function is to set the SELECT function, etc.
How long is it (Block).兹 说 说:
(1) If Timeout is set to "Null", SELECT () will wait until "at least"
A Socket event is set up to return, which is the same as other blocking functions. Select (..., null) / * blocking * /
(2) If the value of timeout is set to {0, 0} (seconds, microseconds), then SELECT () is inspected,
Regardless of whether there is any Socket event, it will immediately return, without staying.
Timeout.tv_sec = timeout.tv_usec = 0;
SELECT (..., & TIMEOUT) / * NON-Blocking * /
(3) If Timout is set to {m, n}, then wait until at least a Socket event
Born, or time (m second n microseconds) will retrn.
Timeout.tv_sec = m;
Timeout.tv_usec = n;
SELECT (..., & Timeout) / * Wait M Secconds n microseconds * /
On UNIX systems, we usually use select () to do "polling" action, check
Whether it occurs; but in the MS Windows 3.x environment, it has been a POLLING actions.
Often care, or may cause the entire Windows system to stop (because the CPU is occupied by your program.
Used); so be sure to pay attention to "Control release" during use, or "Don't set up TIMEOUT
For {0,0} ("because Timeout is set to {0,0}, the internal Winsock system may not call
The Blocking hook is released to release the control.). UNIX system is "Time Sharing"
The formula does not have a similar problem. (The so-called polling action means that you have one in the program.
Back circle, and calling in the round circle to call a letter like Select to do check the action)
SELECT () In addition to checking if Socket is readable; for non-blocking
Socket After calling connect (), you can also use SELECT WRITEFDS to check if the connection is already
Power (when this Non-Blocking Socket is set in WriteFDS, and when Successful is successful);
In addition, we can also use readfds to check if the other party of the TCP Socket is closed (when
This Socket is set in the readfds and is successful by Select, but calls Recv to collect data but returnograph
Time).
(Figure 1. Several different uses of SELECT functions
We must use select () on UNIX systems because there is no WSaasyncSelect ().
The function is to do a polling action; but the Winsock system already has an asynchronous event.
Wsaasyncselect () Voices, in order to make MS Windows "Message Driven"
The environment is more efficient, readers should try to use wsaasyncselect (), and use the SELECT ()
This is also why the biggest purpose of the WSAAsyncSelect () in the beginning. [Change Socket Options "
Winsock 1.1 also provides a setsockopt () file that changes socket options;
There are many projects of Options, and the author just explained only the items that will be used, and the other projects, please readers.
They study themselves.
◎ setsockopt (): Sets Options for Socket.
Format: Int Pascal Far Setsockopt (Socket S, Int Level, INT
Optname,
Const Char Far * Optval, Int Optlen
Parameters: s socket identification code
Level option set by Level (SOL_Socket or
Ipproto_tcp)
Optname Option name
OptVal Option set value
Optlen option set the length of the value
Passage: Success - 0
Failure - Socket_ERROR (Call WsageTlasterror () can know the reason)
Note: This file is used to set some Options for Socket to change its actions. Changeable
Options are: (see Winsock Spec. 54)
Option Type
-------------------------------------------------- ---
SO_BROADCAST BOOL
SO_DEBUG BOOL
SO_DONTLINGER BOOL
SO_DONTROUTE BOOL
SO_keepalive bool
SO_LINGER STRUCT LINGER FAR *
SO_OOBINLINE BOOL
SO_RCVBUF INT
SO_REUSEADDR BOOL
SO_SNDBUF INT
TCP_NODELAY BOOL
(1) SO_BROADCAST - Suitable for UDP Socket. Its meaning is to allow UDP Socket
"Broadcast" message on the Internet.
(2) SO_DONTLINGER - Suitable for TCP Socket. Its meaning is to let Socket in call
When CloseSocket () is turned off, you can immediately call immediately, without waiting until the information is delivered.
Return; CloseSocket () After Return Return, the system will continue to finish the information.
Close this Socket. A TCP Socket is on the preset value of TCP Socket is Don't Linger.
(3) SO_LINGER - Suitable for TCP Socket to set the linger value. If linger
The value is set to 0, then when the CLOSESOCKET () is turned off, if the setput of Socket is Output
Buffer
There is still information, it will be ignored by the system, and it will not be sent, and closesocket () will also horses.
Return; if the linger value is set to n seconds, then the system will try to send it within this time.
Output buffer information, time is delivered or the data is delivered, will call from CloseSocket ()
Return.
(4) SO_REUSEADDR - Allows Socket call bind () to set a already used location (including port number).
Let's take a Linger value to set a socket as an example, see how to call SetsockOpt () in the program.
This function:
Struct linger linger;
Linger.l_onoff = 1; / * Open Linger Settings * /
Linger.l_linger = n; / * Setting the linger time is n second * /
Setsockopt (S, SOL_Socket, So_Linger, & linger, Sizeof (Struct Linger)
Relatively, if we want to know the current set of Option, then you can use it.
GetSockOpt () is made.
◎ getSockopt (): A set value of a SOCKET is currently Option.
Format: Int Pascal Far GetSockOpt (socket S, int level, int Optname,
Char far * optval, int far * optlen
Parameters: s socket identification code
Level option set by Level Option
Optname Option name
OptVal Option set value
Optlen option set the length of the value
Passage: Success - 0
Failure - Socket_ERROR (Call WsageTlasterror () can know the reason)
Note: This file is used to get some Options set values of current sockets.
Similarly, we still take a Linger value to get a socket as an example, how should it be in the program?
Call getsockopt ():
Struct linger linger;
INT OPT_LEN = SIZEOF (Struct Linger);
GetSockopt (S, SOL_Socket, SO_Linger, & linger, & Opt_len)
[What is the blocking hook letter and how to set your own Blocking Hook Funny]
What is the "Blocking Hook" card? Before explanation, we must first analyze it first.
What is the block of blocking functions (such as Accept, Connect, etc.) provided by WINSOCK 1.1
thing?
Inside the Blocking in Winsock Stack, in addition to checking some conditions (such as this should
Whether the use has been called WSAStartup ()? Is the incoming parameter correct? Wait for it, will enter one
Similar to the next round:
FOR (; {
/ * Execute blocking hook letter * /
While (BlockingHook ());
/ * Check if the user has called WSACANCELBLOCKINGCALL ()? * /
IF (Operation_CanceLled ())
Break;
/ * Check whether the action is completed? * /
IF (Operation_Complete ())
Break;
}
Now we can clearly know that there are three important things in the rebound circle of the blocking, (1)
Execute the Blocking Hook Verifier (2) Check if the user calls wsacancelblockingcall ()
Caill the call for this blocking letter? (3) Check if the action of this blocking function has been completed?
Readers must pay attention to the order of different Winsock Stacks in the implementation of these three things may not be
The same; some Winsock Stack may check if the block of blocking is complete,
After executing the Blocking hook in the blocking hook; so the Blocking hook function may not be called. Stay
Will explain the key points of the blocking hook letter, readers can know why the author is in front
I must be very careful when using a polling way.
From the back ring above, we can now know the time of the blocking hook letter to make the system
Waiting for the blocking letter to complete the call before completing, it is not used by our own app.
The Winsock system has a preset blocking hook in the inside of itself; now let's take a look
What does this preset Blocking hook card do?
Bool defaultblockinghook (void) {
MSG msg;
Bool ret;
/ * Get the next message; if you have, you will handle it; if not, you will release the control * /
Ret = (BOOL) PeekMessage (& MSG, NULL, 0, 0, PM_REMOVE);
IF (re) {
TranslateMessage (& MSG);
DispatchMessage (& MSG);
}
Return Ret;
}
Oh! It is important in the blocking hook card that is: letting the blocking letter is waiting
Other messages can be handled before the action is completed, or the CPU control is released so that other applications
There are also opportunities to perform.
Now returning to a little one, please think about it carefully: if you are in a Winsock Stack
In the back ring of the blocking, check if the movement of the blocking function has been completed, then
Whether the Blocking hook is written; then if you may not release the CPU control to make other
What is the opportunity to perform? If we have a loop similar to the following, then the whole
The Windows environment may live because of our program.
FOR (; {
FD_ZERO (& WriteFDs);
FD_SET (S, & Writefds);
Timeout.tv_sec = timeout.tv_usec = 0;
N = SELECT (64, NULL, & WRITEFDS, NULL, & TIMEOUT);
IF (n> 0)
Break;
IF (n == 0) / * Timeout * /
CONTINUE;
...
}
Send (S, Data ...);
In this backset example, we originally want to use Select () and polling to check Socket.
Does there are room to write information in Output Buffer? If Output Buffer is complete,
The SELECT () letter is checked in such a situation, and Timeout is {0,0}, then immediately returnome
0, without calling to the Blocking Hook Function to release the CPU control to give it in the Windows environment.
Hipped (including Winsock's Protocol Stack); because Winsock Kernel cannot send any information in Output buffer because it is not assigned to the CPU time; return from select () back *.
After, return to the front of the ring ring, then call select (), immediately timeout ...; windows
The system is therefore hanned!
What do you need to pay attention to in the Blocking Hook in addition to the problem of CPU control release? Big
The family will look at the back circle of the blocking in front of the blocking letter; the BLOCKING HOOK version is packaged in another
An infinite While round ring. If a Blocking hook version of Return is never 0
If you are always trapped in this infinity circle; so we are designing your own blocking
Hook Functions must also be very careful with this return.
Know the use of Blocking Hook Functions and Design Blocking Hook Functions
How do we replace the original Blocking hook function? That is to use
WsasetBlockingHook () is a function.
◎ WsaseTBlockingHook (): Establish an application designated Blocking Hook.
Farproc Pascal Far WsaseTBlockingHook (FarProc
lpblockfunc)
Number: LPBLOCKFUNC points to the address of the location of the Blocking hook letter to be installed
Passage: Refers to the metrics for the location of a blocking hook letter
Description: This card allows users to set his own blocking hook, for replacement
System preset in the system. The set-in-form will be sent to the "Blocking" action in the application.
Row. The only Winsock interface function that can be called in the BLOCKING HOOK card specified by the user
WSACANCELBLOCKINGCALL ().
Suppose we have designed a blocking hook letter called MyBlockingHook (), then
The method of registering to the Winsock system is as follows: (where _HINST represents this task Instance)
FarProc lpmybkhook = NULL;
LPMYBKHOOK = MakeProcinstance ((FarProc) MyBlockingHook, _HINST);
WsaseTBlockingHook (FARPROC) lpmybkhook;
(Figure 2.) Set your own blocking hook
After setting your own Blocking Hook, we can still use it.
WSAUNHOKBLOCKINGHOK () Versatics to cancel the blocking hook letter we set,
More rebounded in the original system.
◎ WSAUNHOKBLOCKINGHOK (): Restore system preset Blocking Hook Functions.
Format: int Pascal Far WSAUNHOKBLOCKINGHOK (VOID)
Parameter: None
Passage: Success - 0
Failure - Socket_ERROR (Call WsageTlasterror () can know the reason)
Note: This card is canceled the user-set Blocking Hook, while replying to the original preset Blocking Hook Function.
In the end, the author will explain that the blocking hook letter set by the application is only
The application is used in this application; other applications do not execute the Blocking Hook Letter you set
. In addition, if it is not necessary, it is best not to change the BLOCKING HOOK function of the system anyway;
Because once you are not designed, the entire Windows environment may end.
(Figure 3.) This consideration when using your own Blocking hook
[Conclusion]
The four "Winsock Application Design" is over; the author introduces the Winsock API
In addition, you will also design the experience of Winsock.dll in person with yourself and share it; I hope these issues
Chapter, for the domestic WINSOCK 1.1 environment to develop network applications have a little help
help. thank you all.
-
Origin: ● Zucai BBS ● from: 202.121.132.131
? Area: Internet.china is 1,111? Where is Xomo know 1?
Msg #: 2223 date: 24 jun 96 22:29:48
From: bg5hag sky read: Yes replied: no
TO: MARK: SAVE
Subj: Winsock Function (1)
Which is 1y? Where is Xomotice? Where is Xiyomo? Where is Xomo? Where is Xomo?
@Msgid: 6: 653 / 5000.0 31D71C51
Posted by: BG5HAG (SKY) on board 'inet'
Title: Winsock functions (1)
Date: Tue Jun 25 11:39:30 1996
== Lin Jun ==
[Introduction]
The Windows Sockets API interface provided by this system is based on January 20, 1993.
A letter defined in the published Wins 2 (such as appendix); including 30
Berkeley Software Distribution (BSD) in the form of 16 complies with Windows
Mership-Driven features a function of feature.
BSD functions include:
Accept () bind () CloseSocket () connect ()
Getpeername () getsockname () getsockopt () htonl ()
Htons () inet_addr () inet_ntoa () ioctlsocket ()
Listen () ntohl () ntohs () RECV ()
Recvfrom () Seect () send () sendto ()
Setsockopt () SHUTDOWN () Socket () gethostname ()
gethostbyaddr () gethostbyname ()
GetProtobyname () getProtobynumber ()
GetServByName () getServbyport ()
Microsoft Windows-Specific Extensions Funches include:
WsaasyncgetHostByaddr () WSaasyncGetHostByname ()
WSaasyncGetProtobyname () WSAASYNCGETPROTOBYNUMBER ()
WsaasyncgetServbyName () wsaasyncgetServbyport ()
WSAASYNCSELECT () wsacancelasyncRequest () wsacancelblockingcall () wsacleanup ()
Wsagetlasterror () WSAISBLOCKING ()
WsasetBlockingHook () wsasetlasterror ()
WSAStartup () WSAUNHOOKBLOCKINGHOK ()
These API interfaces apply to Internet Protocol Suite (IPS, usually called TCP / IP),
Support Stream (TCP) and DataGram (UDP) Socket.
STREAM (TCP) Socket provides "two-way", "reliable", "order", "no heavy remover"
Data transfer.
DataGram (UDP) Socket provides "two-way" communication, but there is no "reliable", "once
Preface "," no heavy remover ", etc.
Even information may also be omission during transmission.
[Blocking and Non-Blocking mode]
Blocking mode: When the user calls this mode, you will enter the inside of this card until
Conditions or data is completely met to return to the call point.
Non-Blocking mode: When the user calls this mode, enter the inside of this group,
According to the conditions or information at the time, it will not stay in the function or information in the letter.
It is only necessary to respond fully.
Users must pay attention to the blocking mode of Winsock definition with general Unix is not too
with. Winsock definition allows the application to be able to handle it while calling the blocking function.
It information, including keyboard and mouse events; but at this time
Can cancel the original Locking action or use in wsacancelblockingcall ()
WSAISBLOCKING () Functions to check if there is a blocking action is still outside,
"Can't" call other Socket functions before the blocking blocked blocking in the original call,
Otherwise, will fail and generate WSAINPROGRESS errors.
Users call wsacancelblockingcall () written by the blocking action is not
Accept () or select (), then then the only callable socket function is only
CloseSocket (), because the Blocking action that cancels a socket will make it unit
(Indeterminate) status.
[Async (Non-synchronous) mode]
When the user calls this mode, it will not be requested immediately;
After the operation is completed, the system will notify the caller by another way. It is the benefit of users who don't need to wait
Other action or requirements can be done before the reply.
Winsock defined async mode is informing the user in the way "PostMessage"
Has been completed; so when you call such a form, you must inform Windows Sockets DLL Some
News, including the Windows Handle and Information Number of the message.
[Letter of the letter]
[BSD Socket Primary Library]
(1) accept (): Accepts a Socket connection requirement to complete the connection of the Stream Socket.
Format: Socket Pascal Far Accept (Scoket S,
Struct SockAddr Far * Addr,
INT FAR * AddRlen;
Parameters: s socket identification code
AddR storage to the address of the end
Addrlen Addr length passive: success - new socket identification code
Failure - INVALID_SOCKET (Call Wsagetlasterror () can know the reason)
Description: The application of the Server end calls this one to accept the Client side requirements.
Socket connection action; if the SOCKET of the Server is for the Blocking mode, no one
Ask the connection action, then this one of the block functions will return to an error. ACCEPT ()
Covering is a new socket, this socket can not be used to accept other connection requirements; but the original
Sockets can still accept other people's connection requirements.
(2) Bind (): Specifies the local location of the socket (Address).
Format: Int Pascal Far Bind (socket S,
Const struct sockaddr far * name,
INT Namelen;
Parameters: s socket identification code
Name Socket address value, its format
Struct sockaddr {
U_SHORT SA_FAMILY;
Char SA_Data [14];
}
Namelen Name length
Passage: Success - 0
Failure - Socket_ERROR (Call WsageTlasterror () can know the reason)
Note: This one is specified for the local address and port gives an unnamed Socket.
If the user does not at the address or port value, then he can set the location to INADDR_ANY, and
Port is 0; then Windows Sockets will automatically set it properly address and port
(The value between 1024 to 5000), the user can call after this SOCKET is really connected.
Called getSockName () to know the value set.
(3) CloseSocket (): Close a socket.
Format: Int Pascal Far CloseSocket; Socket S);
Parameters: s socket identification code
Passage: Success - 0
Failure - Socket_ERROR (Call WsageTlasterror () can know the reason)
Note: This one is used to close some socket.
If the user originally sets SO_DONTLINGER to the SOCKET to be closed,
After this one, you will reply immediately, but this Sokcet has not yet transferred the data meeting.
It is only closed after delivery.
If the user originally set this socket as SO_Linger, there are two cases:
(a) Timeout is set to 0, this socket is reset immediately, not overlooked or
Not received is fully lost.
(b) Timeout is not 0, will send the information, or wait until TIMEOUT will
shut down.
(4) Connect (): Requires to connect to a socket to the specified other party.
Format: Int Pascal Far Connect (Socket S,
Const struct sockaddr
Far * Name,
INT Namelen;
Parameters: s socket identification code
Name This Socket wants to connect to the other party site
Namelen Name length
Passage: Success - 0
Failure - Socket_ERROR (Call WsageTlasterror () can know the reason)
Description: This file is used to establish a connection to the other party. If the specified object address is 0, the error value will be returned. When the connection is established, the user can use this socket to do transfer or
The received information is used.
(5) getPeername (): Get the other party address of the Socket connected successfully.
Format: Int Pascal Far getPeername (socket S,
Struct SockAddr Far * Name,
INT FAR * NAMELEN;
Parameters: s socket identification code
Name This Socket connection to the other party site
Namelen Name length
Passage: Success - 0
Failure - Socket_ERROR (Call WsageTlasterror () can know the reason)
Note: This one can be used to obtain the site data of the end of the connected Socket.
(6) getSockName (): Get the local location of the socket.
Format: Int Pascal Far getSockName (socket S,
Struct SockAddr Far * Name,
INT FAR * NAMELEN;
Parameters: s socket identification code
Name This Socket LOCAL address
Namelen Name length
Passage: Success - 0
Failure - Socket_ERROR (Call WsageTlasterror () can know the reason)
Description: This file is used to obtain the local order information of the set location or connected SOCKET.
If this Socket is set to INADDR_Addr_any, it will be sent back after the actual establishment is successful.
The right address.
(7) getsockopt (): Requires information on a Socket current status setting.
Format: Int Pascal Far GetSockopt (socket S,
Int Level,
Int Optname,
Char far * Optval,
INT FAR * OPTLEN;
Parameters: s socket identification code
Level option set by the Level option
Optname option name
Optval option setting value
The length of the Optlen option setting value
Passage: Success - 0
Failure - Socket_ERROR (Call WsageTlasterror () can know the reason)
Description: This file is used to get some status settings of the current socket.
Winsock provides Level only SOL_Socket and Ipproto_TCP Optname
The following choices: (see Winsock 29, 30) Definitions)
Value Type
-----------------------------------------------
SO_ACCEPTCONN BOOL
SO_BROADCAST BOOL
* SO_DEBUG BOOL
SO_DONTLINGER BOOL
* SO_DONTROUTE BOOL
* SO_ERROR INT
* SO_KEEPALIVE BOOL
SO_LINGER STRUCT LINGER FAR *
SO_OOBINLINE BOOL
* SO_RCVBUF INT
SO_REUSEADDR BOOL
* SO_SNDBUF INT
SO_TYPE INT
TCP_NODELAY BOOL
(* Table does not provide this feature option)
(8) htonl (): Converts a 32-bit di u_long value by Host's arrangement
NetWork arrangement.
Format: u_long pascal far htonl (u_long hostlong);
Number: Hostlong A 32-bit Yuan Host Arrangement
Passage: A number of 32-bit NetWork arrangements
Description: Because NetWork's arrangement may be different from Host's arrangement,
So we need this one in this one.
(9) HTONS (): Transitions the value of 16-bit dimpity U_SHORT by Host's arrangement
NetWork arrangement.
Format: U_SHORT PASCAL FAR HTONS (u_short hostshort);
Number: Hostshort a 16-bit Host Multiple Mode
Passage value: a number of 16-bit NetWork arrangements
Description: Because NetWork's arrangement may be different from Host's arrangement,
So we need this one in this one.
(10) INET_ADDR (): Converts the location of the string format to a 32-bit Unsigned Long format.
Format: UNSIGNED Long Pascal Far inet_addr (Const Char Far * CP);
Parameters: CP a representative address "Dotted) string
Passage: Success - a unsigned long representing the internet location
Failure - INADDR_NONE
Description: This card translates a "point format" address to the applicable INTENET address.
The "point format" string can be one of the following four ways:
(i) a.b.c.d (ii) a.b.c (iii) A.B (iv) a
(11) INET_NTOA (): Convert a network location into a "point format" string.
Format: Char Far * Pascal Far inet_ntoa (struct in_addr in);
Parameters: in one represents the structure of the internet site
Passage value: success - a "dotted) string representing a representative address
Failed - NULL
Description: This card transfers an Internet address to the "A.b.c.d" string format.
(12) IOCTLSocket (): Controls the mode of the socket.
Format: Int Pascal Far IOCTLSocket (socket S,
Long cmd,
U_long far * argp);
Parameters: s socket identification code
CMD command name
Argp points to the indicator of the CMD parameter
Passage: Success - 0
Failure - Socket_ERROR (Call WsageTlasterror () can know the reason)
Description: This file is used to obtain or set the operation parameters of the socket. The instructions provided are:
(See Winsock Item 1.1 35, 36)
Fionbio - Switch Non-Blocking mode
FionRead - Since Socket, you can read the amount of data available
Siocatmark - OOB data has been read (* does not provide this feature)
(13) Listen (): Set the socket to the listening state, ready to be connected.
Format: Int Pascal Far Listen (Socket S, INT Backlog);
Parameters: s socket identification code
BACKLOG did not really complete the connection (not yet called accept ())
The maximum number of connection requirements for each other
Passage: Success - 0
Failure - Socket_ERROR (Call WsageTlasterror () can know the reason)
Note: Users can use this file to set the socket to enter the listening state, and set up to how many of the plurality of connection requirements that do not really complete the connection before the connection. (The current maximum limit is 5, the most
Small value is 1)
(14) NTOHL (): Converts one 32-bit di u_long's value by NetWork into
Host arrangement.
Format: U_long Pascal Far Ntohl (u_long netlong);
Parameters: Netlong A 32-bit NetWork Arrangement
Passage: A number of 32-bit Yuan Host arrangements
Description: Because NetWork's arrangement may be different from Host's arrangement,
So we need this one in this one.
(15) NTOHS (): Converts the value of 16-bit terminal u_short by NetWork into
Host arrangement.
Format: U_SHORT PASCAL FAR NTOHS (U_SHORT NETSHORT);
Number: Netshort A 16-bit NetWork Arrangement
Passage value: a number of 16-bit Host ranks
Description: Because NetWork's arrangement may be different from Host's arrangement,
So we need this one in this one.
(16) RECV (): Receive information from Socket.
Format: Int Pascal Far Recv (Socket S,
Char Far * BUF,
Int Len,
INT FLAGS);
Parameters: s socket identification code
BUF storage regions received
Length of Len Buf
Flags This card is called
Passage value: success - received the length of the data (0) If the other Socket is closed, it is 0)
Failure - Socket_ERROR (Call WsageTlasterror () can know the reason)
Description: This franchise with DataGram Socket or Stream Socket from the connection
Receive information. For Stream Socket, we can receive the current effective (Available)
Data, but its quantity does not exceed the size of the LEN. If this Socket is set to SO_OOBINLINE,
And the data of Out-of-Band is not read, then only the data of Out-of-Band is taken out.
For the DataGram Socket, only the first DataGram is taken out; if the DataGram is greater than
The storage space provided by the user, then only the size of the space is taken out, how much information
Will be lost, and reply back to the wrong message. The value of Flags can be MSG_Peek, MSG_OOB
(* No combination of this feature is provided). (Refer to Winsock 1.1 version 41)
(17) Recvfrom (): Read a DataGram and store the location where the data source is stored.
Format: Int Pascal Far Recvfrom (socket S,
Char Far * BUF,
Int Len,
Int Flags,
Struct socketaddr far * from
Int far * fromlen;
Parameters: s socket identification code
BUF storage regions received
Length of Len Buf
Flags This card is called
Address of from FROM
Fromlen fromLomlen from
Passage value: success - received the length of the data (0) If the other Socket is closed, it is 0)
Failure - Socket_ERROR (Call WsageTlasterror () can beware of this) Description: This file is used to read the data and record the location where the data source is recorded.
For Stream Socket, its role is the same as RECV (), parameter from and fromlen will not
It is used.
(18) SELECT (): Check if one or more sockets are in a readable, writable or erroneous state.
Format: Int Pascal Far Select (int NFDS,
FD_SET FAR * READFDS,
FD_set far * writefds,
FD_set far * Exceptfds,
Const struct TimeVal Far * Timeout;
Parameters: NFDS This parameter has no effect here.
Readfds To be checked, Sockets
Writefds wants to be checked for Sockets
ExceptFDS is to check if there is a wrong sockets (* no effect)
Timeout This function is waiting. If null is NULL,
Represents Blocking, this franchise will wait until there is an event.
Passage: Success - the total number of Sockets eligible (0 is 0 if Timeout occurs)
Failure - Socket_ERROR (Call WsageTlasterror () can know the reason)
Explanation: Users can use this file to check if Sockets can be read,
Or there is a space that can be written, or there is an error.
(19) Send (): Use the connection type Socket to transfer information.
Format: Int Pascal Far Send (Socket S,
Const Char Far * BUF,
Int Len,
INT FLAGS);
Parameters: s socket identification code
BUF stores the provisional area for information to be transferred
Length of Len Buf
Flags This card is called
Passage value: success - the length of the delivery
Failure - Socket_ERROR (Call WsageTlasterror () can know the reason)
Note: This function is suitable for connecting DataGram or Stream sockets to transfer information.
For DataGram Socket, if the size of DataGram exceeds the limit, will not be sent
Any information, and will return the error value. If the storage space in the transfer system is not
Follow these information to be transmitted, send () will be held by Block, unless the socket is set
Down to non-blocking mode. Users should also pay attention to the success of the send () written, not a table
The information has been successfully sent to each other. The value of Flags can be set to msg_dontroute
(* This feature is not provided) and the combination of MSG_OOB. (See Winsock No. 1.1 48)
(20) Sendto (): Send data to the specified destination.
Format: Int Pascal Far Sendto (Socket S,
Const Char Far * BUF,
Int Len,
Int Flags,
Const struct sockaddr far * to,
int toolen;
Parameters: s socket identification code
BUF stores the provisional area for information to be transferred
Length of Len Buf
Flags This card is called
Address to be delivered to TO
TOLEN TO size
Passage value: success - the length of the delivery
Failure - Socket_ERROR (Call WsageTlasterror () can know the reason)
Description: This function applies to DataGram or Stream Socket to transfer data to the specified address. For DataGram Socket, if the size of DataGram exceeds the limit, will not be sent
Any information, and will return the error value. For Stream Socket, its role is combined with Send ()
The same; parameter TO and TOLEN have no effect here. If it is the transfer (TRANSPORT)
Save space is not enough to store information to be transmitted, Sendto () will be block, unless the
Socket is set to Non-Blocking mode. Users should also pay attention to sendto () functions
It is not expressed that the information has been successfully sent to each other. The value of Flags can be set to msg_dontroute
(* This feature is not provided) and the combination of MSG_OOB. (See Winsock No. 1.1 Edition 51)
(21) Setsockopt (): Set the status of the socket.
Format: Int Pascal Far Setsockopt (Socket S,
Int Level,
Int Optname,
Const Char Far * OptVal,
Int Optlen;
Parameters: s socket identification code
Level option set by the Level option
Optname option name
Optval option setting value
The length of the Optlen option setting value
Passage: Success - 0
Failure - Socket_ERROR (Call WsageTlasterror () can know the reason)
Description: This file is used to set some of the options for Socket to change its actions.
Options that can be changed are: (See Winsock Item 1.1 Edition 54)
Value Type
-----------------------------------------------
SO_BROADCAST BOOL
* SO_DEBUG BOOL
SO_DONTLINGER BOOL
* SO_DONTROUTE BOOL
* SO_KEEPALIVE BOOL
SO_LINGER STRUCT LINGER FAR *
SO_OOBINLINE BOOL
* SO_RCVBUF INT
SO_REUSEADDR BOOL
* SO_SNDBUF INT
TCP_NODELAY BOOL
(* Table does not provide this feature option)
(22) Shutdown (): Stop the function of the Socket to receive / transmit.
Format: Int Pascal Far Shutdown (socket s, int how);
Parameters: s socket identification code
How represents to stop those actions
Passage: Success - 0
Failure - Socket_ERROR (Call WsageTlasterror () can know the reason)
Description: This file is used to stop the function of subsequent receipt or delivery of the socket.
If the value is 0, the information is no longer received.
If the value is 1, the information is not allowed.
If the value is 2, it is no longer received and the data is not transferred.
The shutdown () function does not close socket, so the resource occupied by this socket must
It is necessary to be released after calling CloseSocket ().
(23) Socket (): Establish Socket.
Format: Socket Pascal Far Socket (int Af,
Int Type,
INT protocol;
Parameters: AF currently only provides PF_INET (AF_INET)
Type Socket (SOCK_STREAM, SOCK_DGRAM)
Protocol Communication Agreement (if the user is not specified, set to 0)
Passage value: success - Socket identification code
Failure - INVALID_SOCKET (Call Wsagetlasterror () can know the reason)
Note: This file is used to create a socket and build the resources used for this Socket.
Socket types can be Stream Socket or DataGram Socket.
(24) gethostbyaddr (): Utilize the location of the Host to get the information of this host.
Format: Struct Hostent Far * Pascal Far
GethostByaddr (Const Char Far * Addr, Int Len, Int Type);
Parameters: AddR NetWork Alignment
Length of Len Addr
TYPE PF_INET (AF_INET)
Passage: Success - pointing to Struct Hostent
Struct hostent {
CHAR FAR * h_name;
Char Far * Far * h_aliases;
Short h_addrtype;
Short h_gength;
Char Far * Far * h_addr_list;
}
Failure - NULL (Call wsagetlasterror () can know the reason)
Note: This file is used to get other information from Host, such as the name of Host,
Alias, location, length, etc.
(25) gethostByname (): Use a host name to get the information of the host.
Format: Struct Hostent Far * Pascal Far
GethostByName (Const Char Far * name);
Parameters: Name Host Name
Passage: Success - pointing to Struct Hostent
Struct hostent {
CHAR FAR * h_name;
Char Far * Far * H_A
Like a frog jumps in the bottom of the well, when can I jump out ............................
2002-12-12 08:22 # 35
Wind and high
Middle school
member
UID 186
Essence 6
Points 2088
Post 990
Read permission 40
Registration 2002-11-4
Thirty articles
Simple and practical network programming debugging tool
Author: Yang sandbank
Debugging is a big difficult relationship between programming, or even more difficult to exceed the programming itself, and the network application is
It is more difficult to find with ordinary debugging tools with ordinary debugging tools.
logical error. Especially when developing a web application based on a Client / Server structure,
Tracking, interrupt output and other traditional debugging means are difficult to find out the error. I am developing
When the MUD client program like ZMUD, it once debugged four or five because of a character back.
hour.
---- If a network intermediate program like pipeline is developed, the client and service party
The process is recorded in turn, and then offline analysis is often received.
---- The program structure is very simple, consisting of two processes, and resides after the background starts. father
The process monitors local predetermined temporary ports and receives a request to the service party after receiving the client request.
After the connection is established, the generated sub-process is responsible for receiving the client to output and transmit it to the service party;
Inheriting the Socket descriptor of the Parent process, responsible for receiving the server output and transmitted to the client. Overall knot
As shown below: ()
---- The program records the communication content of the two parties at the scheduled file of the work directory while completing the communication.
In the middle, the crown is in the prefix of Client and Server to distinguish between different information sources. It is worth noting that the standard I / O library function is buffered, the order of communication cannot be recorded, and the original I / O (Read / Write) must be used.
---- Result file records in bytes, including transmission of ASCII codes and corresponding display
character. Take the process of writing Telnet as an example, to create a login connection in the Telnet protocol
The previous negotiation process can use this procedure.
---- Assuming that the executable file name of this program is Netpipe, local IP is 172.10.33.28, far away
The Telnet server IP is 172.20.8.144, and the program is pre-specified to monitor local port 8888. First of all
Row Netpipe, then run Telnet:
$ NETPIPE 172.20.8.144 23 &
$ telnet 172.10.33.28 8888
.
.
.
Ctrl-d
The subsequent record file will be displayed as follows:
Server:
255
253
twenty four
255
253
32
255
253
35 #
255
253
39 '
Client:
255
251
.
.
.
---- This Telnet meeting in appearance does not have any difference with the direct Telnet, the only difference
This communication will generate a record file. This program uses GCC 2.3 in Linux Kernel 2.2.3
Translation is passed, it is convenient to port to different systems, including Windows 95 / NT.