VC + + Programming Winsock---socket (socket) __ Programming

Source: Internet
Author: User
Tags see definition htons
Socket (socket)

First look at the definition:

typedef unsigned int u_int;
typedef u_int SOCKET;
Socket is equivalent to the network communication at both ends of the socket, as long as the other side of the socket and their sockets have a communication connection, both sides can send and receive data. The definition is similar to a file handle.

There are five different types of sockets:

1, streaming socket (stream socket)
Defined:

#define SOCK_STREAM 1
Streaming sockets provide bidirectional, sequential, repeatable, and undocumented data flow services that are suitable for handling large amounts of data. It is a connection-oriented, must establish data transmission link, but also must verify the data transmitted to ensure the accuracy of the data. Therefore, the system overhead is large.

2, datagram socket (datagram socket)

Defined:

#define SOCK_DGRAM 2
Datagram sockets also support bidirectional data flow, but do not guarantee the accuracy of the transmitted data, but retain the record boundaries. Because the datagram socket is not joined, such as a join at broadcast time, there is no guarantee that the receiving end is listening. Datagram socket transmission efficiency is high.

3. Original socket (Raw-protocol interface)

Defined:

#define SOCK_RAW 3
The original socket holds the full IP header in the packet, and the previous two sockets receive only user data. Therefore, the data can be analyzed by the original socket.
The other two kinds of sockets are not commonly used, here is not introduced.

The files required for socket development (take Winsock V2.0 as an example):

Header file: Winsock2.h

Library files: ws2_32.lib

Dynamic Library: W32_32.dll

A number of important definitions

1, the basic definition of data type: This everyone can understand.

typedef unsigned char U_char;
typedef unsigned short u_short;
typedef unsigned int u_int;
typedef unsigned long u_long;
2, the network address of the data structure, there is an old and a new one, please note that if you want to know why,
Please send an email to Bill Gate. is actually the IP address of the computer, but generally do not use a point separate IP
Address, of course, also provides some conversion functions.

The old network address structure is defined as a 4-byte union:

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 is used for most TCP & IP code * *
The following lines are omitted, which is of little use anyway.
};
In fact, no such trouble at all, please see below:

Definition of the new network address structure:
Very simply, a unsigned long integer unsigned long. For example: What is the IP address of a 127.0.0.1 network address? Please 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]; /* bytes of direct address * *
};
Sa_family is a network address type, typically af_inet, which indicates that the socket is communicating in an Internet domain, and the address structure varies depending on the protocol that is selected, so another sockaddr_in structure with the same size as the address structure is generally more common. The SOCKADDR_IN structure is used to identify the addresses under the TCP/IP protocol. In other words, this structure is the generic 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 a network address type and must be set to Af_inet. Sin_port as a service port, be careful not to use a fixed service port, such as Port 80 of HTTP. If the port is set to 0, the system automatically assigns a unique port. SIN_ADDR is a unsigned long IP address. Sin_zero is a fill field that is used purely to guarantee the size of the structure.

A function that converts a commonly used dot-separated IP address to a unsigned long IP address:

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, or all computers, are represented.

#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 * 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 the list of host aliases.
H_addrtype is the address type.
H_length is the address type.
H_addr_list is an IP address, including a list of addresses if the host has more than one network card.
There are also a few similar structures, which are not covered here.

5, the 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, we can see it.

Properties of sockets

In order to use sockets flexibly, we can set the properties of the socket.

1, the property content:

Allow debug output
#define SO_DEBUG 0x0001/* Turn on Debugging info Recording * *
Whether to listen for mode
#define SO_ACCEPTCONN 0x0002/* Socket has had listen () * *
Socket to address binding to other sockets
#define SO_REUSEADDR 0x0004/* Allow local address reuse * *
Stay Connected
#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 * *
Use loop back not through hardware
#define SO_USELOOPBACK 0x0040/* Bypass hardware when possible * *
Current delay value
#define SO_LINGER 0x0080/* Linger on close if data present * *
Whether to include Out-of-band data
#define So_oobinline 0x0100/* Leave received OOB data in line * *
Disable 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 status and clear */
Socket type
#define SO_TYPE 0x1008/* Get socket TYPE * *
2. Read the socket properties:

int getsockopt (SOCKET s, int level, int optname, char FAR * optval, int FAR * Optlen)
S to read the properties of the socket. Levels are the level of the socket option, most of which are proprietary to specific protocols and sockets. If the IP protocol should be ipproto_ip.

Optname is the name of the Read option
Optval is the buffer pointer that holds the value of the option.
Optlen is the length of the buffer
Usage:

int ttl=0; Read TTL value
int rc = getsockopt (S, Ipproto_ip, Ip_ttl, (char *) &ttl, sizeof (TTL));
From MS Platform SDK 2003
3, set the socket properties:

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 rank of the socket option, as above.
Optname is the name of the setting option
Optval is the buffer pointer that holds the value of the option.
Optlen is the length of the buffer

Usage:

int ttl=32; Set TTL value
int rc = setsockopt (S, Ipproto_ip, Ip_ttl, (char *) &ttl, sizeof (TTL));
Steps for using sockets

1, start Winsock: Initialize the Winsock DLL, negotiate the Winsock version support and allocate the necessary
Resources. (server side and client)

int WSAStartup (WORD wversionrequested, Lpwsadata lpwsadata)

Wversionrequested for the intended load Winsock version, generally the following settings:
Wversionrequested=makeword (2,0)
or direct assignment: wversionrequested=2

Lpwsadata information about the version loaded after the socket is initialized 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 load succeeds after the data is:

Wversion=2 indicates that the loaded version is 2.0.
whighversion=514 indicates that the current system supports the maximum socket version of 2.2.
szdescription= "WinSock 2.0"
Szsystemstatus= "Running" indicates that it is running.
Imaxsockets=0 indicates that the maximum number of sockets opened at the same time is 0, which means there is no limit.
Imaxudpdg=0 indicates that the maximum number of datagrams opened at the same time is 0, which means there is no limit.
Lpvendorinfo is not used to specify information reservation for the manufacturer.
The function uses the method:

WORD Wversion=makeword (2,0);
Wsadata Wsdata;
int nresult= WSAStartup (wversion,&wsdata);
if (Nresult!=0)
{
Error handling
}
2, Create sockets: (Server side and client)

Socket socket (int AF, int type, int protocol);
AF is a network address type, typically af_inet, that is used in an Internet domain.
Type is a socket, as described earlier.
Protocol for the specified network protocol, generally for IPPROTO_IP.
Usage:

SOCKET Sock=socket (AF_INET,SOCK_STREAM,IPPROTO_IP);
if (Sock==invalid_socket)
{
Error handling
}
3. Binding of Sockets: Bind the local address to the socket you created. (server side and client)

int bind (SOCKET s, const struct SOCKADDR FAR * name, int namelen)
S is the 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 then coerced into the SOCKADDR structure.
Namelen is the length of the address structure.

Usage:

Sockaddr_in addr;
Addr. Sin_family=af_inet;
Addr. Sin_port= htons (0); Guaranteed 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 monitoring: (server-side)

int Listen (SOCKET s, int backlog)
S is a bound but not joined socket.
Backlog This parameter is important to specify the maximum queue length that is waiting for a join because the server can generally
To provide multiple connections.
Usage:

int Nresult=listen (s,5)//Up to 5 connections
if (nresult==socket_error)
{
Error handling
}
5, socket waiting for the connection:: (server-side)

Socket accept (socket s, struct sockaddr FAR * addr, int FAR * Addrlen)
S is a socket in the listening mode.
SOCKADDR returns the network address of the client after a successful reception.
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 Link: Connect two sockets to prepare for communication. Client

int Connect (SOCKET s, const struct SOCKADDR FAR * name, int namelen)
S is the created socket that you want to link to.
Name is the socket address to which you want 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); Guaranteed 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 send data: (server side and client)

int send (SOCKET s, const char FAR * buf, int len, int flags)
s a socket that is listening on the server side.
BUF is the pointer to send the data buffer.
Len is the length of the data buffer to send.
Flags send tags for data.
The return value is the number of characters that sent the data.

Here's the send tag, as are the receive tags discussed in the following 8:

The flag value must be 0 or a combination of the following definitions: 0 means no special behavior.

#define MSG_OOB 0x1/* Process out-of-band Data * *
#define Msg_peek 0x2/* PEEK at incoming message * *
#define Msg_dontroute 0x4/* Send without using routing tables */
Msg_oob indicates that the data should be sent out, and the so-called Out-of-band data is the TCP emergency data.
Msg_peek means that the useful data is copied into the buffer but not removed from the system buffer.
Msg_dontroute indicates that the package should not be routed out.

Usage:

Char buf[]= "Xiaojin";
int Nresult=send (S,buf,strlen (BUF));
if (nresult==socket_error)
{
Error handling
}
8, Socket Data reception: (client)

int recv (SOCKET s, Char FAR * buf, int len, int flags)
s a socket that is ready to receive data.
BUF is the buffer that is ready to receive data.
Len is ready to receive the size of the data buffer.
Flags receive tokens for data.
Returns the number of characters that the value receives from the data.

Usage:

Char mess[1000];
int Nresult =recv (s,mess,1000,0);
if (nresult==socket_error)
{
Error handling
}
9. Interrupt Socket Connection: Notifies server side or client to stop receiving and sending data. (server side and client)

int shutdown (SOCKET s, int how)
S is the socket for which you want to disconnect.
How to describe prohibited operations, values are: 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, close the socket: release the resources occupied. (server side and client)

int closesocket (SOCKET s)
s for the socket to be closed.

Usage:

int Nresult=closesocket (s);
if (nresult==socket_error)
{
Error handling
}

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.