C language Winsock Study Notes page 1/2

Source: Internet
Author: User
Tags see definition set socket

Author: Xiao Jin

Socket)

◆ First look at the definition:
Typedef unsigned int u_int;
Typedef u_int socket;
◆ Socket is equivalent to a socket at both ends of network communication. As long as the socket of the other party is connected to its own socket, both parties can send and receive data. Its definition is similar to the definition of a file handle.

◆ Socket has five different types:

1. stream socket)
Definition:
# Define sock_stream 1
Streaming sockets provide bidirectional, ordered, non-repetitive, and non-record-Free Data Stream Services, suitable for processing large amounts of data. It is link-oriented. Data Transmission links must be established and the transmitted data must be verified to ensure data accuracy. Therefore, the system overhead is high.

2. datagram socket)

Definition:
# Define sock_dgram 2
The datagram socket also supports two-way data streams, but does not guarantee the accuracy of the transmitted data, but retains the record boundaries. Because the datagram socket is connectionless, such as the connection during broadcast, It is not guaranteed whether the receiving end is listening. Datagram socket transmission efficiency is relatively high.

3. Raw-Protocol Interface)

Definition:
# Define sock_raw 3
The original socket stores the complete IP header in the data packet. The first two sockets can only receive user data. Therefore, data can be analyzed through the original socket.
The other two sockets are not commonly used. We will not introduce them here.

◆ Files required for socket Development (taking 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 types: You can understand it at a 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 has an old one and a new one. Please note that if you want to know why,
Please send an email to Bill Gate. It is actually the IP address of the computer, but generally do not use IP addresses separated by dots
Of course, some conversion functions are also provided.

◆ The definition of the old network address structure is a 4-byte combination:
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 lines are omitted, which is useless.
};
In fact, you don't need to be so troublesome. Please refer to the following:

◆ Definition of the new network address structure:
It is very simple, that is, an unsigned long integer. For example, what is the network address with the IP address 127.0.0.1? See definition:
# Define inaddr_loopback 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, generally af_inet, indicating that the socket communicates in the Internet domain. The address structure varies with the selected protocol, therefore, another sockaddr_in structure with the same size as the address structure is more common. The sockaddr_in structure is used to identify the address under the TCP/IP protocol. In other words, this structure is a general socket address structure, and the following sockaddr_in is a socket address structure dedicated to 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 and must be set to af_inet. Sin_port is the service port. Do not use a fixed service port, such as http port 80. If the port is set to 0, the system automatically assigns a unique port. Sin_addr is an unsigned long IP address. Sin_zero is the filling field, which is used to ensure the size of the structure.

◆ Function for converting commonly used IP addresses separated by dots to IP addresses 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 to inaddr_any, all IP addresses, that is, all computers.
# Define inaddr_any (u_long) 0x00000000
4. Host address:

First look at the definition:
Struct hostent {
Char far * h_name;/* official name of Host */
Char far * h_aliases;/* alias list */
Short h_addrtype;/* Host address type */
Short h_length;/* length of address */
Char far * h_addr_list;/* list of addresses */
# Define h_addr h_addr_list [0]/* address, for backward compat */
};
H_name indicates the host name.
H_aliases is the host alias list.
H_addrtype is the address type.
H_length is the address type.
H_addr_list is the IP address. If the host has multiple NICs, it includes the address list.
There are also several similar structures, which will not be described here.

5. Definitions of common TCP/IP protocols:
# 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 protocol.

Socket attributes

To use sockets flexibly, we can set its attributes.

1. Attribute content:
// Allow debugging output
# Define so_debug 0x0001/* Turn on debugging info recording */
// Whether the listening mode is used
# Define so_acceptconn 0x0002/* socket has had listen ()*/
// The socket is bound to the address of other sockets
# Define so_reuseaddr 0x0004/* allow local address reuse */
// Keep the connection
# Define so_keepalive 0x0008/* keep connections alive */
// Do not route out
# Define so_dontroute 0x0010/* just use interface addresses */
// Set to broadcast
# Define so_broadcast 0x0020/* permit sending of broadcast msgs */
// Hardware used for loopback failure
# Define so_useloopback 0x0040/* bypass hardware when possible */
// Current delay Value
# Define so_linger 0x0080/* Linger on close if data present */
// Whether to add out-of-band data
# Define so_oobinline 0x0100/* Leave initialized ed OOB data in line */
// Disable the linger Option
# Define so_dontlinger (INT )(~ So_linger)
// Sending buffer Length
# Define so_sndbuf 0x1001/* Send buffer size */
// Length of the receiving buffer
# Define so_rcvbuf 0x1002/* receive buffer size */
// Sending timeout
# Define so_sndtimeo 0x1005/* Send timeout */
// Receiving 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 socket attributes:
Int getsockopt (socket S, int level, int optname, char far * optval, int far * optlen)
S is the socket for reading properties. Level is the level of socket options, most of which are proprietary to specific protocols and sockets. If the IP protocol is ipproto_ip.
Optname is the name of the read Option
Optval is the buffer pointer for storing option values.
Optlen indicates the buffer length.
Usage:
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 socket attributes:
Int setsockopt (socket S, int level, int optname, const char far * optval, int optlen)
S is the socket for which you want to set properties.
Level is the level of socket options. The usage is the same as above.
Optname is the name of the Setting option.
Optval is the buffer pointer for storing option values.
Optlen indicates the buffer length.

Usage:
Int TTL = 32; // set the TTL value
Int rc = setsockopt (S, ipproto_ip, ip_ttl, (char *) & TTL, sizeof (TTL ));
Socket usage steps

1. Start Winsock: Initialize Winsock DLL, negotiate with Winsock versions to support and assign necessary
Resources. (Server and client)
Int wsastartup (word wversionrequested, lpwsadata)

To load the Winsock version, wversionrequested is generally set as follows:
Wversionrequested = makeword (2, 0)
Or assign a value directly: wversionrequested = 2

Lpwsadata is the version information loaded after the socket is initialized. It 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 after successful loading is:
Wversion = 2 indicates that the loaded version is 2.0.
Whighversion = 514 indicates that the maximum socket version supported by the current system is 2.2.
Szdescription = "Winsock 2.0"
Szsystemstatus = "running" indicates that the instance is running.
Imaxsockets = 0 indicates the maximum number of sockets opened at the same time. 0 indicates no limit.
Imaxudpdg = 0 indicates the maximum number of opened data packets at the same time. 0 indicates no limit.
Lpvendorinfo is not used and is reserved for vendor-specified information.
How to use this function:
Word wversion = makeword (2, 0 );
Wsadata wsdata;
Int nresult = wsastartup (wversion, & wsdata );
If (nresult! = 0)
{
// Handle errors
}
2. Create a socket: (server and client)
Socket socket (int af, int type, int Protocol );
AF is a network address type, generally af_inet, indicating that it is used in the Internet domain.
Type is the socket type, which has been described earlier.
Protocol is the specified network protocol, generally ipproto_ip.
Usage:
Socket sock = socket (af_inet, sock_stream, ipproto_ip );
If (sock = invalid_socket)
{
// Handle errors
}
3. Socket binding: bind the local address to the created socket. (Server and client)
Int BIND (socket S, const struct sockaddr far * Name, int namelen)
S is the socket that has been created.
The name is the socket address structure and the sockaddr structure. As discussed above, we generally use sockaddr_in
Structure, which is forcibly converted to the sockaddr structure after use.
Namelen is the length of the address structure.
Usage:
Sockaddr_in ADDR;
ADDR. sin_family = af_inet;
ADDR. sin_port = htons (0); // ensure the 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)
{
// Handle errors
}
4. Socket listening: (server)
Int listen (socket S, int backlog)
S is a bound but not connected socket.
Backlog specifies the maximum queue length waiting for connection. this parameter is very important because the server can
To provide multiple connections.
Usage:
Int nresult = listen (S, 5) // up to 5 connections
If (nresult = socket_error)
{
// Handle errors
}
5. Socket waiting for connection: (server side)
Socket accept (socket S, struct sockaddr far * ADDR, int far * addrlen)
S is the socket in listening mode.
Sockaddr is the network address of the client returned after receiving the message.
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)
{
// Handle errors
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.