Simple socket () programming

Source: Internet
Author: User
Tags htons

Client:

1, socket (int af, int type, int protocol)

The socket () function is used to assign a description word of a set of interfaces and the resources it uses, based on the specified address family, data type, and protocol. If the Protocol protocol is unspecified (equals 0), the default connection method is used. Only one protocol is supported for a particular set of interfaces that use a given address family. However, the address family can be set to Af_unspec (unspecified) so that the protocol parameters are specified. The protocol number is specific to the communication domain in which the communication is made.

Sock_stream provides an ordered, reliable, bidirectional, and connection-based byte stream, using an out-of-band data transfer mechanism to use TCP for Internet address families. The Sock_stream type of socket interface is a full bidirectional byte stream. For a stream class socket interface, it must be in a connected state before receiving or sending data. Use the Connect () call to establish a connection to another set of interfaces, after which the data can be transmitted using Send () and recv (). When the session ends, call Close (). Out-of-band data is received as specified by Send () and recv (). The communication protocol that implements the SOCK_STREAM type socket interface guarantees that the data will not be lost or duplicated.

If the terminal protocol has buffer space and the data cannot be sent successfully at a certain time, the connection is considered to be interrupted and subsequent calls will also be returned with a wsaetimeout error.

The SOCK_DGRAM supports non-connected, unreliable, and datagram services that use a fixed-size (usually very small) buffer, using UDP for the Internet address family.

2, int connect (int s, const struct SOCKADDR * name, int namelen)
Used to create a connection to the specified external port. The s parameter specifies an unbound datagram or stream class socket interface. If the socket interface is not bundled, the system assigns a unique value to the local association and sets the socket interface as bundled. For the Stream class socket interface (SOCK_STREAM type), the name is used to establish a connection to a remote host, and once the socket call returns successfully, it can send and receive data. For the Datagram Class socket interface (SOCK_DGRAM type), it is set to a default destination address and used for subsequent send () and recv () calls.

3, int send (SOCKET s, const char far *buf, int len, int flags);

send simply copy the data in the BUF to the rest of the space, note that the send buffer is not sent to the other side of the transmission of the data, but the protocol, send just copy the data in the BUF to the rest of the send buffer of S.

#include <stdio.h>#include<sys/types.h>#include<sys/socket.h>#include<string.h>#include<arpa/inet.h>//added the header file, seraddr.sin_addr.s_addr = inet_addr (Severip); no warning#defineSeverip "192.168.31.103"#defineSeverport 9003intSOCKFD =-1;intRET =-1;Charsendbuf[ -];structSockaddr_in cliaddr = {0};structSockaddr_in seraddr = {0};intMain () {//Create socketSOCKFD = socket (af_inet, Sock_stream,0);//Address family: af_inet represents IPV4; //Service: Sock_stream//protocol default: 0    if(SOCKFD <0) {perror ("Socket"); return-1; } printf ("SOCKFD =%d\n", SOCKFD); //initiate a connection on a socketseraddr.sin_family =af_inet; Seraddr.sin_port=htons (Severport); Seraddr.sin_addr.s_addr=inet_addr (Severip); RET= Connect (SOCKFD, (Const structsockaddr*) &seraddr,sizeof(SERADDR)); if(Ret <0) {perror ("Connect"); return-1; } printf ("Connect Result,ret =%d.\n", ret); //Communication---Send content//strcpy (sendbuf, "Hello World");printf"***************************************\n");  while(1) {printf ("Please input your content to send:"); memset (SendBuf,0,sizeof(SENDBUF)); scanf ("%s", SENDBUF); RET= Send (SOCKFD, SendBuf, strlen (SENDBUF),0); printf ("***************************************\n"); }    return 0;}

Client

1. The bind () function establishes a local bundle (host address/port number) for a set of interfaces by assigning a local name to an unnamed socket interface

2, int listen (SOCKET sockfd, int backlog);
Backlog connection request queue (queue of pending connections)
Listen the status of a connection request in a socket function that allows a socket to be listening for incoming calls

3, int accept (int sockfd, struct sockaddr *addr, socklen_t *addrlen);
This function extracts the first connection from the waiting connection queue of SOCKFD, creates a new nested interface with SOCKFD and returns a handle. If there are no waiting connections in the queue and the socket is blocked, then accept () blocks the calling process until a new connection occurs. If the socket is non-blocking and there are no waiting connections in the queue, accept () returns an error code. The socket interface that has been accepted cannot be used to accept new connections, and the original set of interfaces remains open.

4, int recv (_in_ SOCKET s, _out_ char *buf, _in_ int len, _in_ int flags)
The execution flow of the recv function that synchronizes the socket. When the application calls the RECV function: (1) recv waits for the data in the send buffer of s to be passed by the Protocol, if the Protocol has a network error while transmitting the data in the send buffer of S, then the RECV function returns SOCKET_ERROR ; (2) If there is no data in the transmit buffer of s or the data is successfully sent by the protocol, recv first checks the socket s receive buffer, if the s receive buffer does not have data 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, and the actual receive data is the protocol to complete)

#include <stdio.h>#include<sys/types.h>#include<sys/socket.h>#include<arpa/inet.h>#include<string.h>#defineServer_ip "192.168.31.103"#defineServer_port 9003#defineBacklog 100structSockaddr_in seraddr = {0};structSockaddr_in cliaddr = {0};intSOCKETFD =-1, CLIFD =-1;intRET =-1;Charrecvbuf[ -];socklen_t Len;intMain () {//Create SocketSOCKETFD = socket (af_inet, Sock_stream,0); if(Socketfd <0) {perror ("Fail to creat socket"); return-1; } printf ("socketfd=%d.\n", SOCKETFD); //assigning a name to a socketseraddr.sin_family =af_inet; Seraddr.sin_port=htons (Server_port); Seraddr.sin_addr.s_addr=inet_addr (SERVER_IP); RET= Bind (SOCKETFD, (Const structsockaddr*) (&AMP;SERADDR),sizeof(SERADDR)); if(Ret <0) {perror ("Fail to bind"); return-1; }        //ListenRET =Listen (socketfd, backlog); if(Ret <0) {perror ("Listen"); return-1; }        //Wait for clientCLIFD = Accept (SOCKETFD, (structsockaddr*) (&AMP;CLIADDR), &Len); if(Clifd <0) {perror ("Wait for client"); return-1; } printf ("Wait for client SUCCESSFUL,FD =%d.\n", CLIFD); //Communication---Receive contentprintf"***************************************\n");  while(1) {ret= Recv (CLIFD, Recvbuf,sizeof(RECVBUF),0); printf ("The receive substance is [%s].\n", RECVBUF); memset (Recvbuf,0,sizeof(RECVBUF)); }        return 0;}


Simple socket () programming

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.