Socket notes ~

Source: Internet
Author: User

Before using socket in Windows, you must initialize the Windows Socket library. Otherwise, socket () will return socket_error (-1)

 
Wsadata;
 
Word wversionrequested;// Version
 
Wversionrequested = makeword (1, 1 );// Version info
 
// Initialize Windows Socket Library
Wsastartup (wversionrequested, & wsadata );

In general, the NetworkProgramIs composed of two parts-the client and the server. The creation steps are generally:

Server socket --> bind --> listen-> Accept

Client socket --> connect

SocketSocket(INT domain, int type, int Protocol)

    • Domain: indicates the Communication Co-family (af_unix and af_inet) used by the host where the network program is located. af_unix can only be used for inter-process communication between a single UNIX system, whileAf_inet is for the InternetAllows communication between remote hosts.
    • Type: communication protocol used by our network program (sock_stream, sock_dgram, etc)Sock_streamIndicates that we useTCPProtocol, which provides sequential, reliable, bidirectional, and connection-oriented bit streams.Sock_dgramIndicates that we useUDPProtocol, which only provides fixed-length, unreliable, and connectionless communication.
    • Protocol: because we have specified the type, we generally only need to replace it with 0. The following is the Protocol definition of from Winsock. h.

# Define ipproto_ip 0/* dummy for IP */

# Define ipproto_icmp 1/* Control Message Protocol */

# Define ipproto_igmp 2/* Internet Group Management Protocol */

# Define ipproto_ggp 3/* gateway ^ 2 (Deprecated )*/

# Define ipproto_tcp 6/* tcp */

# Define ipproto_pup 12/* pup */

# Define ipproto_udp 17/* User datasync Protocol */

# Define ipproto_idp 22/* xns IDP */

# Define ipproto_nd 77/* Unofficial net disk proto */

# Define ipproto_raw 255/* Raw IP packet */

# Define ipproto_max 256

E.g.

 
Slisten = socket (af_inet, sock_stream, ipproto_tcp );

The socket file descriptor is returned successfully, and-1 is returned if the request fails.

IntBind(INT sockfd, struct sockaddr * my_addr, int addrlen)

    • Sockfd: The file descriptor returned by a socket call.
    • Addrlen: the length of the sockaddr structure.
    • My_addr: a pointer to sockaddr. sockaddr is defined in Winsock. h:
 
StructSockaddr {
 
U_short sa_family;/* Address family */
 
CharSa_data [14];/* Up to 14 bytes of direct address */
};

However, due to system compatibility, we generally do not need this header file, instead of using another structure (struct sockaddr_in). sockaddr_in is defined in Winsock. h:

 
/*
 
* Socket address, Internet style.
 
*/
StructSockaddr_in {
 
ShortSin_family;
 
U_short sin_port;
 
StructIn_addr sin_addr;
CharSin_zero [8];
 
};

We mainly use the Internet, so sin_family is generally af_inet, and sin_addr is set to inaddr_any, which indicates that it can communicate with any host, and sin_port is the port number we want to listen. sin_zero [8] is used for filling. bind binds the local port with the file descriptor returned by the socket. 0 is returned for success, and-1 is returned for failure.

Sin_port is the network byte sequence, and sin_addr.s_addr is also the same. When processing your own IP address and/or port, some work can be automatically processed.

My_addr.sin_port = 0;/* randomly select an unused port */

My_addr.sin_addr.s_addr = inaddr_any;/* use your own IP Address */

By assigning 0 to my_addr.sin_port, you tell BIND () to select an appropriate port. Similarly, set my_addr.sin_addr.s_addr to inaddr_any, and you will tell it to automatically fill in the IP address of the machine on which it runs.

E.g.

Localaddr. sin_addr.s_addr = inet_addr (ipaddr );
 
Localaddr. sin_family = af_inet;
 
Localaddr. sin_port = htons (portnum );
 
BIND (S _,(StructSockaddr *) & localaddr,Sizeof(Localaddr ));

Because the client does not need a fixed port number, you do not need to call BIND (). The client port number is automatically allocated by the kernel. If the server does not call BIND (), the kernel will automatically allocate a listening port to the server. The port number is different each time the server is started, and the client will have trouble connecting to the server.

IntListen(Socket S, int backlog );

    • S: Socket file descriptor after bind
    • Backlog: sets the maximum length of request queuing. When multiple client programs are connected to the server, this indicates the length of the queue that can be introduced. (How many TCP connections can be monitored)
    • The listen function changes the BIND file descriptor to the listening socket. An error is returned.-1 is returned.

E.g.

 
Listen (slisten, 3 );

 

SocketAccept(Socket S, struct sockaddr * ADDR, int * addrlen );

    • S: The socket file descriptor after listen
    • ADDR and addrlen are used to fill in the client program. The server only needs to pass the pointer. BIND, listen, and accept are functions used by the server. When an accept is called, the server program will be blocked until a client program sends a connection. when accept succeeds, the final server file descriptor is returned. At this time, the server can write information to this descriptor. -1 is returned when a failure occurs.

E.g.

Sclient = accept (slisten ,(StructSockaddr *) & client, & iaddrsize );

 

IntConnect(Socket S, const struct sockaddr * Name, int namelen );

    • S: file descriptor returned by socket
    • Name: stores the connection information of the server. The name is the address of the server.
    • Namelen: Name Length
    • The connect function is used by the client to connect to the server. 0 is returned when the connection succeeds, and-1 is returned when the file descriptor for communication with the server fails.

E.g.

 
Memset (& server, 0,Sizeof(Sockaddr_in ));
Server. sin_family = af_inet;
 
Server. sin_addr.s_un.s_addr = inet_addr (server_address );
 
Server. sin_port = htons (port );
 
Connect (sclient ,(StructSockaddr *) & server,Sizeof(Sockaddr_in ));

 

IntSend(Socket S, const char * Buf, int Len, int flags );

    • S: Socket file descriptor
    • Buf: data to be sent
    • Len: the length of the sent data
    • Flag: Used to affect the behavior of the Peer socket. It is generally set to 0. (Here we will discuss it with flag)
    • If the message is sent successfully, the actual sending length is returned. If the message fails, the value-1 (socket_error) is returned)

The send function only copies the data in the Buf to S.Sending BufferBut the data is not necessarily uploaded to the other end of the connection immediately. Note that not sending transmits the data in the sending buffer of S to the other end of the connection, but the Protocol. Sending only copies the data in the Buf to the remaining space of the sending buffer of S. The network error encountered during transmission will return socket_error in the next socket function.

Note: In Unix systems, if the network is disconnected when sending data while waiting for the send protocol, the process that calls send will receive a sigpipe signal. By default, the process processes the signal and terminates the process.

 

IntRecv(Socket S, char * Buf, int Len, int flags );

    • S: Socket file descriptor
    • Buf: the buffer Buf for storing read data
    • Len: Maximum buffer Buf Length
    • Flags: Same as above
    • Returns the number of bytes that are actually read into the buffer. Or-1 is returned when an error occurs.

When the application calls the Recv function, the Recv waits for the data in the s sending buffer to be transmitted by the Protocol. If the Protocol encounters a network error when sending data in the s sending buffer, then the Recv function returns socket_error. If no data is in the sending buffer of s or the data is successfully sent by the protocol, the Recv checks the receiving buffer of socket s first, if there is no data in the s receiving buffer or the Protocol is receiving data, the Recv waits until the Protocol receives the data. When the Protocol receives the data, the Recv function copies the data in the s receiving buffer to the Buf (Note that the data received by the protocol may be longer than the Buf length. In this case, you must call the Recv function several times to copy the data in the s receiving buffer.The Recv function only copies data, and the protocol is used to actually receive data.), The Recv function returns the actual number of bytes of copy. If a Recv error occurs during copy, socket_error is returned. If the Recv function is interrupted while waiting for the Protocol to receive data, 0 is returned.

 

IntSendto(Socket S, const char * Buf, int Len, int flags, const struct sockaddr * To, int tolen );

    • S: Socket file descriptor
    • Buf: buffer that contains the data to be sent
    • Len: Maximum buffer Buf Length
    • Flags: Call method flag
    • TO: (optional) pointer to the address of the Target Interface
    • Tolen: the length of the address to indicate.

The sendto () function is mainly used to send a datagram to the socket interface of the sock_dgram type set interface to the specified end of the to parameter (destination IP address and port information. For interfaces of the sock_stream type, the to and tolen parameters are ignored. In this case, sendto () is equivalent to send ().

For the sock_dgram interface, you must note that the length of the sent data should not exceed the maximum length of the IP packet of the Communication Subnet. The maximum length of the IP package is in the imaxudpdg element of the wsadata returned by the wsastartup () call. If the data is too long to automatically pass the lower-layer protocol, the wsaemsgsize error is returned and the data will not be sent.

If no error occurs, send () returns the total number of sent data (note that this number may be smaller than the size specified in Len ). Otherwise, the socket_error is returned. The application can obtain the corresponding error through wsagetlasterror ().Code

 

IntRecvfrom(Socket S, char * Buf, int Len, int flags, struct sockaddr * From, int * fromlen );

    • S: Socket file descriptor
    • Buf: receiving data buffer
    • Len: Maximum buffer Buf Length
    • Flags: Call Operation Method
    • From: (optional) pointer pointing to the buffer with the source address
    • Fromlen :( optional) pointer, pointing to the FROM Buffer Length Value

For interfaces of the sock_stream type, the from and fromlen parameters are ignored. If the from field is non-zero and the Set interface is of the sock_dgram type, the address of the sending data source is copied to the corresponding sockaddr structure. The size of the structure when fromlen points to the value is initialized. When the call is returned, it is modified according to the space occupied by the actual address.

If no data is to be read, unless it is in non-blocking mode, the set of interfaces will always wait for the arrival of data, and the socket_error error will be returned. The error code is wsaewouldblock. You can use select () or wsaasynselect () to know when data arrives.

If no error occurs, recvfrom () returns the number of bytes read. If the connection has been terminated, 0 is returned. Otherwise, the socket_error is returned. The application can obtain the error code through wsagetlasterror.

 

Note: The above Code uses the definition in Winsock. H, which is slightly different from winsock2.h. The differences are as follows:

    • Winsock. h uses the legendary Berkeley socket in wsock32.lib, developed by BSD socket in UNIX
    • Use winsock2.h with ws2_32.lib

For most Windows applications, Winsock2 provides new functions for new protocols, such as Bluetooth. Winsock2 also provides the LSP mechanism, the cool thing about this is that you can create your own layers which will in turn get called by the Winsock implementation when any application callthe function you layered. think of it as an easy way to hook any Winsock function.

Winsock2 is completely backward compatible. Winsock should be considered for use only when you are preparing to develop on a platform that does not support Winsock2.

 

From wiki:

Microsoft implementations
    • Microsoft did not supply an implementation of WinSock 1.0.
    • Version 1.1 of WinSock was supplied in an add-on Package (called Wolverine) for Windows for workgroups (code namedSnowball). It was an integral component of Windows 95 and Windows NT from versions 3.5 and onwards (the initial implements cially available version of Windows NT, Version 3.1, included only a proprietary and quite incomplete implementation of TCP/IP Based on the at&t UNIX System V "streams" API [Citation needed]).
    • Version 2.1 of WinSock was supplied in an add-on package for Windows 95. it was an integral component of Windows 98, Windows NT 4.0, and all subsequent Windows releases. (Microsoft did not supply implementations of WinSock 2 for Windows 3.x or Windows NT 3. X .)
    • Recent versions of WinSock 2.x have been delivered with new Windows releases or as part of service packs.
    • WinSock 2 is extensible by a mechanic known as a layered service provider (LSP ). winsock LSPs are available for a wide range of useful purposes, including Internet parental controls, web content filtering, QoS etc. the layering order of all providers is kept in the Winsock catalog. in previous versions of Windows, removing a buggy LSP cocould result in refreshing uption of the Winsock catalog in the registry, potentially resulting in a lossAll network connectivity. Winsock in Windows XP Service Pack 2, Windows Server 2003 Service Pack 1 and all later Windows operating systems has the ability to self-heal after a user uninstallsuch an LSP.

 

Reference:

Network socket programming guide: this document is a guide, not a reference. If you are new to socket programming and want to find an entry book, you are my reader. But this is not a complete socket programming book.

Linux C programming all-in-one learning> 2. TCP-based network programs> Chapter 1 socket programming

Two main methods of UDP: sendto and recvfrom

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.