Winsock learning notes (1)
Socket (socket) ◆ First definition: typedef unsigned int u_int; typedef u_int socket; ◆ Socket is equivalent to the socket of both ends of the network communication, as long as the other Socket is connected to the communication, the two sides can send and receive data . It defines the definitions similar to the file handle. ◆ Socket has five different types: 1, stream socket definition: #define Sock_Stream 1 Flow socket provides two-way, orderly, no duplicate and non-recorded data stream services Suitable for processing a lot of data. It is a connection-oriented, a data transfer link must be established, and it is also necessary to verify the transmitted data to ensure accuracy of the data. Therefore, the system overhead is large. 2, Data Support Set (DATAGRAM SOCKET) Definition: #define Sock_DGRAM 2 Data Supply Setup also supports two-way data streams, but does not guarantee the accuracy of transferring data, but retains the record boundary. Since the data settles are unconnected, such as broadcast, it is not guaranteed whether the receiving end is listening. Data report sets are relatively high. 3. Raw-protocol interface definition: #define Sock_RAW 3 The original socket saves the full IP header in the packet, and the front two sockets can only receive user data. Therefore, the data can be analyzed by the original socket. The other two sockets are not common, and it will not be introduced here. ◆ Socket development must be required (in Winsock V2.0 as an example): header file: Winsock2.H library file: WS2_32.lib Dynamic Library: W32_32.dll Some important definitions 1. Basic definition of data type: This I will understand it at first glance. Typef unsigned char u_CHAR; typef unsigned short u_st; typef unsigned long u_int; typef unsigned long u_long; 2, network address data structure, there is an old and a new, please pay attention, if you want to know why, please send an email Give Bill Gate. In fact, it is the computer's IP address, but it is generally not used to separate IP addresses, and some conversion functions are also provided. ◆ The definition of the old network address structure is a 4-byte combination: struct in_addr {union {structure {u_bhar s_b1, s_b2, s_b3, s_b4;} s_un_b; struct {u_short s_w1, s_w2;} s_un_w; u_long s_addr;} S_un; #define s_addr s_un.s_addr / * can be used for most TCP & IP code * /// The following line will omit, anyway, it is useless. }; It is actually don't have to be so troublesome, please see below: ◆ The definition of the new network address structure: very simple, is an unsigned long and unsigned long.
For example: What is the network address of the IP address 127.0.0.1? Please see: #define INADDR_LOOPBACK 0x7F0000013, Socket Address Structure (1), SockAddr Structure: Struct SockAddr {U_SHORT SA_FAMILY; / * Address Family * / CHAR SA_DATA [14]; / * Up to 14 Bytes of Direct Address * / }; sa_family is the network address type, typically an AF_INET, indicating that the socket is communicating in the Internet domain, which varies with the selected protocol, and therefore, the other is the same SOCKADDR_IN structure as the address structure. For common, the SockAddr_in structure is used to identify the address under the TCP / IP protocol. In other words, this structure is a universal Socket address structure, and the following SockAddr_in is a Socket address structure specifically for the Internet domain. (2), sockaddr_in structure strunt sockaddr_in {short sin_family; u_short sin_port; struct in_addr sin_addr; char sin_zero [8];}; sin _family is the network address type, must be set to AF_INET. SIN_PORT is the service port, not to use the fixed service port, such as the port 80 of HTTP, etc. If the port is set to 0, the system automatically assigns a unique port. SIN_ADDR is an IP address of a unsigned long. SIN_ZERO is the fill field, which is purely used to ensure the size of the structure. ◆ Switch the IP address that is commonly used to convert the IP address of the unsigned long type: unsigned long inet_addr (Const Char Far * CP) Usage: unsigned long addr = inet_addr ("192.1.8.84") ◆ If you set SIN_ADDR settings For INADDR_any, all IP addresses are megadownloadwable. #define inaddr_any (u_long) 0x000000004, Host address: Struct Hostent {char far * h_name; / * official name of host * / char far * far * h_aliases; / * alias list * / short h_addrtype; / * Host Address Type * / Short H_LENGTH; / * LENGTH OF ADDRESS * / CHAR FAR * FAR * H_ADDR_LIST; / * list of addresses * / # define h_addr h_addr_list [0] / * address, for backward compat * /}; h_name is the host name . H_Aliases is a list of alias. h_addrtype is the address type. H_Length is the address type. h_addr_list is an IP address, and if the host has multiple NIC, it includes a list of addresses. There are also several similar structures, which will not be introduced here. 5, common TCP / IP protocol definition: #define ipproto_ip 0 #define ipproto_icmp 1 #define ipproto_igmp 2 #define ipproto_tcp 6 #define ipproto_udp 17 #define ipproto_raw 255 specifically what protocol, everyone will know.
The properties of the socket For flexible use socket, we can set it with its properties. 1, attribute content: // Allow debug output #define so_debug 0x0001 / * Turn on debugging info recording * // // // is listening mode #define so_acceptconn 0x0002 / * Socket HAS HAD LISTEN () * /// Socket with other sets address Sockets binding #define SO_REUSEADDR 0x0004 / * allow local address reuse * /// keeping 0x0008 / * keep connections alive connection #define SO_KEEPALIVE * /// do not route through #define SO_DONTROUTE 0x0010 / * just use interface addresses * / // Set to broadcast #define so_broadcast 0x0020 / * permit sending of broadecast msgs * /// Use loopback not passed hardware #define so_useloopback 0x0040 / * bypass hardware atile * /// Current delay value #define so_linger 0x0080 / * linger On Close if data present * // / 加 带 数据 数据 数据 # # # # 长 长 长 长 长 长 长 长 长 长 长 长 长 长 长 长 长 长 长 长 长 长 # # 长 长 # 长define SO_SNDBUF 0x1001 / * send buffer size * /// receive buffer length #define SO_RCVBUF 0x1002 / * receive buffer size * /// transmission timeout #define SO_SNDTIMEO 0x1005 / * send timeout * /// reception timeout #define SO_RCVTIMEO 0x1006 / * Receive Timeout * /// Error status #define so_error 0x1007 / * get error status and clear * /// Socket type #define SO_ TYPE 0X1008 / * GET Socket Type * / 2, read the socket property: int GetSockopt (socket s, int level, int ptname, char far * optval, int far * Optlen) is a socket that wants to read attributes. Level is the level of socket options, most is proprietary of specific protocols and sockets. If the IP protocol should be ipproto_ip. Optname is a buffer pointer to the name of the option to read options. Optlen is the length usage of the buffer: int TTL = 0; // read TTL value int RC = GetSockOpt (s, ipproto_ip, ip_ttl, (char *) & ttl, sizeof (ttl)); // From MS Platform SDK 20033, Set the socket property: int Setsockopt (Socket S, INT Level, int Optname, Const Char Far * OptVal, int Optlen) Sockets to set the properties. Level is the level of the socket option, usage. Optname is the buffer pointer for the setting option OptVal to the storage option value.
Optlen is the length usage of the buffer: int TTL = 32; // Set TTL value int RC = setsockopt (s, ipProto_ip, ip_ttl, (char *) & ttl, sizeof (ttl)); Use Step 1 of the socket 1, start Winsock: Initialize Winsock DLL, negotiates the version of Winsock supports and assigns the necessary resources. (Server and client) int WSAStartup (WORD wVersionRequested, LPWSADATA lpWSAData) wVersionRequested is intended load Winsock version, generally set as follows: wVersionRequested = MAKEWORD (2,0) or direct assignment: wVersionRequested = 2 LPWSADATA Socket initialization after loading version information is defined as follows: typedef struct WSAData {WORD wVersion; WORD wHighVersion; char szDescription [WSADESCRIPTION_LEN 1]; char szSystemStatus [WSASYS_STATUS_LEN 1]; unsigned short iMaxSockets; unsigned short iMaxUdpDg; char FAR * lpVendorInfo;} WSADATA, FAR * Lpwsadata; if the data is subsequent after the load is: wversion = 2 indicates that the load version is 2.0. WHIGHVERSION = 514 indicates that the current system supports Socket's highest version of 2.2. Szdescription = "Winsock 2.0" szsystemStatus = "running" means running. iMaxSockets = 0 indicates that the maximum number of Sockets simultaneously opened, and there is no limit to 0. iMaxudpdg = 0 indicates that the maximum number of dataginary data simultaneously opened, and there is no limit to 0. LPVENDORINFO is not used, specifying information reserved for vendors. This function uses: Word WVersion = MakeWord (2,0); WSADATA WSDATA; INT NRESULT = WSASTARTUP (WVERSION, & WSDATA); if (NRESULT! = 0) {// Error handling} 2, create a socket: (server) End and client) socket socket (int AF, int type, int protocol); AF is a network address type, typically AF_INET, indicating that in the Internet domain. TYPE is a socket type, which has been introduced. Protocol is generally ipproto_ip for the specified network protocol. Usage: Socket Sock = Socket (AF_INET, SOCK_STREAM, IPPROTO_IP); if (Sock == Invalid_Socket) {// Error Processing} 3, the binding of the socket: Bind the local address to the created socket. (Server and Client) Int Bind (Socket S, Const Struct Sockaddr Far * Name, Int Namelen) is a socket that has been created. Name is the Socket address structure, for the SockAddr structure, as discussed earlier, we generally use the SockAddr_in structure, which is used to convert to the SockAddr structure. Namelen is the length of the address structure.
Usage: sockaddr_in addr; addr; sin_family = afd_inet; addr. Sin_port = htons (0); // guarantee byte order addr. Sin_addr.s_addr = inet_addr ("192.1.8.84") int NRESULT = Bind (s, (sockaddr * ) & addr, sizeof (sockaddr); if (nresult == Socket_ERROR) {// Error handling} 4, socket listening: (server side) int Listen (socket s, int backlog) S is bound but Unconnected socket. BACKLOG is very important for the maximum queue that is waiting for the join, because the server can typically provide multiple connections. Usage: int NRESULT = Listen (s, 5) // Up to 5 connection IF (NRESULT == Socket_ERROR) {// Error handling} 5, socket waiting connection:: (Server) Socket Accept (Socket S, Struct SockAddr Far * Addr, int far * addrlen) S is a socket that is in listening mode. SockAddr returns the network address of the client after receiving success. Addrlen is the length of the network address. Usage: SockAddr_in Addr; Socket S_D = Accept (S, SockAddr *) & addr, sizeof (sockaddr)); if (s == invalid_socket) {// Error handling} 6, socket connection: Two sets Words are connected to prepare to communicate. (Client) int Connect (Socket S, Const Struct Sockaddr Far * Name, Int Namelen) is the created socket that is coming to connect. Name is a Socket address that wants to connect. Namelen is the length of the structure of the Socket address. Usage: SockAddr_in addr; addr; sin_family = afd_inet; addr. Sin_port = htons (0); // guarantee byte order addr. Sin_addr.s_addr = htonl (inaddr_any) // guaranteed byte order int NRESULT = Connect (s, SockAddr *) & addr, sizeof (sockaddr)); if (nresult == socket_error) {// error handling} 7, socket sending data: (server side and client) int send (Socket S, Const Char Far * BUF , Int LEN, int flags) S is the socket that is listening to the server. BUF is a pointer to the data buffer. LEN is the length of the transmitted data buffer. Flags send tags for data. The return value is the number of characters that send data. ◆ Here you talk about this transmission mark, the received tags discussed below: The FLAG value must be 0 or the combination as defined: 0 indicates no special behavior. #define msg_oob 0x1 / * process out-of-band data * / * peek at incoming message * / # define msg_dontrol_ / * send without using routing tables * / msg_oob indicates that the data should be sent outside, the so-called belt The external data is TCP emergency data. MSG_peek means that the useful data is copied into the buffer, but does not delete it from the system buffer. MSG_DONTROUTE means not going out of the package.