Winsock learning notes (1)

xiaoxiao2021-03-06  40

source:

http://www.vckbase.com/document/viewdoc/?id=1035

WinSock study notes (a) Author: Xiao Jin Socket (socket) ◆ Look at the 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 connection, both 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. Typedef unsigned char u_char;

Typedef unsigned short u_short;

Typedef unsigned int u_int;

Typedef unsigned long u_long; 2, the data structure of the network address, there is an old and a new, please pay attention, if you want to know why, please email 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 joint: struct in_addr {

Union {

Struct {u_char 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 be omitted, no use, no use.

}; 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 the definition: #DEfine INADDR_LOPBACK 0x7f000001 3, 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 struct 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 What is the specific agreement? Everyone knows. The properties of the socket For flexible use socket, we can set it with its properties. 1. Properties content: // Allow debug output

#define so_debug 0x0001 / * Turn on debugging info recording * /

/ / Do you listen to mode?

#define so_acceptconn 0x0002 / * socket HAS HAD LISTEN () * /// Sockets Binds with other sockets

#define so_reuseaddr 0x0004 / * ALLOW local address reuse * /

/ / Keep connection

#define so_keepalive 0x0008 / * Keep Connections Alive * /

/ / Don't route

#define so_dontroute 0x0010 / * Just Use interface addresses * /

// Set to broadcast

#define so_broadcast 0x0020 / * permit sending of broadecast msgs * /

// Use loopback from hardware

#define so_useloopback 0x0040 / * Bypass Hardware When Possible * /

// Current delay value

#define so_linger 0x0080 / * linger on close if data present * /

/ / Do you join an external data?

#define so_oobinline 0x0100 / * Leave received Oob Data in line * /

// Disable the linger option

#define so_dontlinger (int) (~ so_linger)

// Send buffer length

#define so_sndbuf 0x1001 / * send buffer size * /

/ / Receive buffer length

#define so_rcvbuf 0x1002 / * Receive buffer size * /

// Send timeout time

#define so_sndtimeo 0x1005 / * Send timeout * /

// Receive timeout time

#define so_rcvtimeo 0x1006 / * Receive Timeout * /

// Error status

#define so_error 0x1007 / * get error stat STATUS AND CLEAR * /

// Socket type

#define so_type 0x1008 / * get socket type * / 2, read the socket property: int GetSockopt (socket S, int level, int iptname, char far * optval, int far * Optlen) is a socket for reading 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 the name of the read option

OptVal is a buffer pointer that stores option values.

Optlen is the length usage of the buffer: int TTL = 0; // read the TTL value

INT RC = GetSockopt (s, ipproto_ip, ip_ttl, (char *) & ttl, sizeof (ttl));

// From MS Platform SDK 2003 3, 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 Skats: Start Winsock: Initialize Winsock DLL, negotiate Winsock's version support and assign the necessary resources . (Server and Client) INT WSASTARTUP (Word WVersionRequested, LPWSADATA LPWSADATA) WVersionRequested is usually set as follows:

WVersionRequested = MakeWord (2,0)

Or directly value: wversionRequested = 2

LPWSADATA is the following information to initialize the version of the socket, 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 is used: Word WVersion = MakeWord (2,0);

Wsadata WSDATA;

INT NRESULT = WSAStartup (WVersion, & WSDATA);

IF (NResult! = 0)

{

// Error handling

} 2, create a socket: (server side and client) Socket Socket (int Af, int type, int protocol);

AF is the network address type, generally 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 handling

} 3, the binding of the socket: Bind local addresses to the created socket. (Server and Client) INT Bind (Socket S, Const Struct Sockaddr Far * Name, Int Namelen)

s is a socket that has been created.

Name is the Socket address structure, for the SockAddr structure, as discussed earlier, we generally use SockAddr_in

The structure is used to convert to the SockAddr structure in use.

Namelen is the length of the address structure.

Usage: sockaddr_in addr; addr. Sin_family = af_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, the listening of the socket: (server side) int Listen (socket s, int backlog) s is a binding but not connected 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 connections

IF (NResult == Socket_ERROR)

{

// Error handling

} 5, socket waits:: (Server) Socket Accept (socket S, Struct SockAddr Far * Addr, Int Far * Addrlen) S is a socket that is in the 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: connect two sockets 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 = af_INet;

Addr. sin_port = htons (0); // guarantee byte order

Addr. sin_addr.s_addr = htonl (inaddr_any) / / guarantee byte order

INT NRESULT = Connect (s, (sockaddr *) & addr, sizeof (sockAddr));

IF (NResult == Socket_ERROR)

{

// Error handling

} 7, socket transmission data: (server side and client) int send (socket s, const charf, int LEN, int flags) Sockets for server-side synapses. 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. Usage: char buf [] = "xiaojin"; int NRESULT = SEND (S, BUF, Strlen (buf));

IF (NResult == Socket_ERROR)

{

// Error handling

} 8, the data reception of the socket: (client) int RECV (socket S, Char Far * BUF, INT LEN, INT FLAGS) S is a socket that is ready to receive data. BUF is a buffer that is ready to receive data. LEN is the size of the receiving data buffer. Flags receives tags for data. Returns the number of characters of the received data. Usage: char mess [1000];

INT NRESULT = RECV (S, Mess, 1000, 0);

IF (NResult == Socket_ERROR)

{

// Error handling

} 9, interrupt socket connection: Notify the server or the client to stop receiving and transmitting data. (Server and Client) INT Shutdown (Socket S, INTHOW) S is a socket to interrupt the connection. How to describe the description, the value is: SD_RECEIVE, SD_SEND, SD_BOTH. #define SD_RECEIVE 0x00

#define sd_send 0x01

#define SD_BOTH 0x02 Usage: int NRESULT = Shutdown (s, sd_both);

IF (NResult == Socket_ERROR)

{

// Error handling

} 10, turn off the socket: release the resources occupied. (Server and Client) INT CloseSocket (Socket S) S is a socket that wants to close. Usage: int NRESULT = CloseSocket (s);

IF (NResult == Socket_ERROR)

{

// Error handling

}

Author information Xiao Jin unit: Nanjing Zhongcai Food Co., Ltd. Information Department Email: xiaoj@njb.swirebev.com Phone: 025-58642091

转载请注明原文地址:https://www.9cbs.com/read-55403.html

New Post(0)