Experience with Windows Socket API

Source: Internet
Author: User
Tags terminates htons

This is my experience in the process of Ms-windows and Hp-unix network programming, which is only for your reference. The socket function mentioned in this article, if not specifically stated, refers to the Windows socket API.

First,WSAStartup function
int WSAStartup (
WORD wversionrequested,
Lpwsadata Lpwsadata
);
A program that uses the socket must call the WSAStartup function before using the socket. The first parameter of the function indicates the version of the socket that the program requests to use, where the high byte indicates the secondary version, the low byte indicates the major version, and the operating system returns the version information of the requested socket using the second parameter. When an application calls the WSAStartup function, the operating system searches for the appropriate socket library based on the requested socket version, and then binds the found socket library into the application. The application can then invoke the other socket functions in the requested socket library. The function returns 0 after successful execution.
Example: If a program wants to use the 2.1 version of the socket, then the program code is as follows
wversionrequested = Makeword (2, 1);
Err = WSAStartup (wversionrequested, &wsadata);

Second, WSACleanup function
int wsacleanup (void);
After the application finishes using the requested socket library, call the WSACleanup function to unbind the socket library and release the system resources that the socket library occupies.

Third, the socket function
Socket Socket (
int AF,
int type,
int protocol
);
The application calls the socket function to create a socket that can communicate with the network. The first parameter specifies the protocol family of the communication protocol used by the application, and for the TCP/IP protocol family, the parameter is pf_inet; the second parameter specifies the socket type to be created, the stream socket type is sock_stream, and the datagram socket type is SOCK_DGRAM The third parameter specifies the communication protocol used by the application. The function returns the descriptor of the newly created socket if the call succeeds, and returns Invalid_socket if it fails. A socket descriptor is a value of an integer type. There is a Socket descriptor table in the process space for each process, which holds the corresponding relationship between the socket descriptor and the socket data structure. There is one field in the table that holds the descriptor for the newly created socket, and the other field holds the address of the socket data structure, so that its corresponding socket data structure can be found based on the socket descriptor. Each process has a socket descriptor in its own process space but the socket data structure is in the kernel buffer of the operating system. Here is an example of creating a flow socket:
struct Protoent *ppe;
        Ppe=getprotobyname ("TCP");
        SOCKET listensocket=socket (pf_inet,sock_stream,ppe->p_proto);

Four, closesocket function
int Closesocket (
SOCKET s
);
The Closesocket function is used to close a descriptor for the s socket. Since each process has a socket descriptor table, each of the socket descriptors in the tables corresponds to a socket data structure in the operating system buffer, so there may be several socket descriptors pointing to the same socket data structure. There is a single field in the socket data structure that holds the referenced number of the structure, that is, how many socket descriptors point to the structure. When the Closesocket function is called, the operating system checks the value of the field in the socket data structure first, and if 1, indicates that only one socket descriptor points to it, so the operating system clears the corresponding table entry in the Socket descriptor table first. and release s corresponding socket data structure, if the field is greater than 1, then the operating system only clears s in the socket descriptor table of the corresponding table entry, and the s corresponding socket data structure of the reference number minus 1.
The Closesocket function returns 0 if execution succeeds, otherwise returns SOCKET_ERROR.

v. Send function
int Send (
SOCKET S,
const char FAR *buf,
int Len,
int flags
);
Both the client and server applications use the Send function to send data to the other end of the TCP connection. The client program typically sends a request to the server with the Send function, and the server usually sends a reply to the client using the Send function. The first parameter of the function specifies the send-side socket descriptor, the second parameter indicates a buffer that holds the data to be sent by the application, the third parameter indicates the number of bytes of data actually to be sent, and the fourth parameter is generally 0. This describes only the execution flow of the Send function that synchronizes the socket. When the function is called, send compares the length of the data to be sent, Len, and the size of the send buffer of the socket s, and if Len is greater than the length of the send buffer of s, the function returns SOCKET_ERROR, if Len is less than or equal to the length of the send buffer of S, Then send first check whether the protocol is sending the data in the send buffer, if it is waiting for the protocol to send out the data, if the protocol has not begun to send the data in the send buffer or s of the send buffer does not have data, then send compares s of the send buffer of the remaining space and Len, If Len is larger than the remaining space, send waits for the protocol to send the data in the transmit buffer of s, if Len is less than the amount of space left, send will simply copy the data in the BUF to the remaining space (note that it is not the send buffer that sends the data to the other end of the connection). Instead of the protocol, send simply copy the data from the BUF to the remaining space in the send buffer of s). If the Send function copy data succeeds, it returns the number of bytes actually copied, and if send has an error in copy data, then send returns SOCKET_ERROR, if the network is disconnected while the send waits for the protocol to transmit the data. Then the Send function also returns SOCKET_ERROR. Note that the Send function returns the data in the BUF after it has been successfully copied to the remaining space of S's send buffer, but at this point the data is not necessarily immediately passed to the other end of the connection. If the protocol has a network error during subsequent transfers, the next socket function returns SOCKET_ERROR. (Each of the socket functions except for send will have to wait for the data in the socket's send buffer to continue before execution, and if a network error occurs while waiting, the socket function returns SOCKET_ERROR)
Note: Under UNIX systems, if send is disconnected when the network is waiting for the protocol to transmit data, the process that calls send receives a sigpipe signal, and the process terminates the default processing for that signal.

VI recv function
    int recv (
       SOCKET s,       
      char far *buf,   
      int len,        
      int flags       
   );
    both client and server applications use the RECV function to receive data from the other end of the TCP connection. The first parameter of the function specifies the receive end socket descriptor, the second parameter indicates a buffer, which is used to hold the data received by the RECV function, the third parameter indicates the length of the buf, and the fourth parameter is generally 0. This describes only the execution flow of the recv function that synchronizes the socket. When the application calls the Recv function, recv waits for the data in the send buffer of s to be passed by the protocol, and if the protocol has a network error while transmitting the data in the send buffer of S, then the RECV function returns SOCKET_ERROR, If there is no data in the transmit buffer of s or after the data has been successfully sent by the protocol, RECV checks the socket s receive buffer, if there is no data in the s receive buffer or the protocol is receiving data, then recv waits until the protocol receives the data. When the protocol takes over the data, the RECV function will copy the data from the receive buffer of S to BUF (note that the data received by the Protocol may be greater than the length of the buf, so in this case a few recv functions are called to copy the data from the receive buffer of S. The recv function is just copy data, the real receive data is the protocol to complete, the RECV function returns the number of bytes it actually copied. If the recv error occurs in copy, it returns SOCKET_ERROR if the Recv function waits for the protocol to receive data The network has been interrupted, then it returns 0.
Note: Under UNIX systems, if the RECV function waits for the protocol to receive data while the network is disconnected, the process that calls Recv receives aSigpipe Signal, the process terminates the default processing of the signal.

Seven, bind function
int bind (
SOCKET S,
const struct SOCKADDR far *name,
int Namelen
);
When a socket is created, there is a default IP address and a default port number in the socket data structure. A service program must call the BIND function to bind it to an IP address and a specific port number. Client programs generally do not have to call the bind function to bind their sockets to IP addresses and break numbers. The first parameter of the function specifies the socket descriptor to bind to, and the second parameter specifies a SOCKADDR structure, which is defined as:
struct SOCKADDR {
U_short sa_family;
Char sa_data[14];
};
sa_family Specifies the address family, and af_inet the socket for the TCP/IP protocol family. When binding a socket on a TCP/IP protocol family, we typically use a different address structure:
struct SOCKADDR_IN {
Short sin_family;
U_short Sin_port;
struct IN_ADDR sin_addr;
Char Sin_zero[8];
};
Where Sin_family af_inet;sin_port indicates the port number; There is only one unique field s_addr in the sin_addr struct that represents the IP address, which is an integer and is generally used as a function inet_ Addr () converts an IP address in the form of a string into an integer value of unsigned long and then resets to S_ADDR. Some servers are multi-host, there are at least two network cards, then the service program running on such a server can put htonl (inaddr_any) to S_ADDR for its socket, the benefit is that regardless of the network segment of the client program can communicate with the service program If you only bind a fixed IP address to the socket that is running a service program on a multiple host, only the client program that is on the same network segment as the IP address can communicate with the service program. We populate the Sin_zero array with zeros to make the size of the SOCKADDR_IN structure consistent with the size of the SOCKADDR structure. The following is an example of a bind function call:
struct sockaddr_in saddr;
saddr.sin_family = af_inet;
Saddr.sin_port = htons (8888);
SADDR.SIN_ADDR.S_ADDR = htonl (Inaddr_any);
Bind (Listensocket, (struct sockaddr *) &saddr,sizeof (SADDR));

Viii. Listen function
int Listen (SOCKET s, int backlog);
The service program can call the Listen function to make its stream socket s in the listening state. The stream socket s in the listening state maintains a client connection request queue, which accommodates up to a backlog of client connection requests. If the function succeeds, it returns 0, or socket_error if execution fails.

Nine, the Accept function
SOCKET Accept (
SOCKET S,
struct sockaddr far *addr,
int far *addrlen
);
The service program calls the Accept function to remove the first customer request from the Client connection request queue of the stream socket s in the listening state, and creates a new socket to create the connection channel with the client socket, and if the connection succeeds, returns the descriptor of the newly created socket, The newly created socket is later exchanged for the data with the client socket, and if it fails, returns Invalid_socket. The first parameter of the function specifies a stream socket in the listening state; the operating system uses the second parameter to return the address structure of the newly created socket, and the operating system uses the third parameter to return the length of the address structure of the newly created socket. The following is an example of a call to accept:
struct sockaddr_in serversocketaddr;
int Addrlen;
Addrlen=sizeof (SERVERSOCKETADDR);
Serversocket=accept (Listensocket, (struct sockaddr *) &serversocketaddr,&addrlen);

X. Connect function
int Connect (
SOCKET S,
const struct SOCKADDR far *name,
int Namelen
);
The client program calls the Connect function to connect the client socket s to a service socket on a specific port on the computer specified by name. If the connection succeeds, connect returns 0, and if it fails, it returns SOCKET_ERROR. Here is an example:
struct sockaddr_in daddr;
memset (void *) &daddr,0,sizeof (DADDR));
Daddr.sin_family=af_inet;
Daddr.sin_port=htons (8888);
DADDR.SIN_ADDR.S_ADDR=INET_ADDR ("133.197.22.4");
Connect (clientsocket, (struct sockaddr *) &daddr,sizeof (DADDR));


Experience with Windows Socket API

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.