Linux in the way of C, the creation of the server is mainly composed of several modules: the creation of the section Word, the encapsulation IP address and port number, and socket connection method, the binding socket and the encapsulated struct sockaddr_in,
Listen to the execution, open the server side, accept client links, accept clients messages, send service-side messages.
Create a section Word:
Code:
int socket;
Socket = new socket (af_inet,sock_stream,0);
Comments:
1.af_inet:ipv4 Network protocol
2.af_inet6:ipv6 Network protocol
3.sock_stream: Link-oriented TCP protocol
4.sock_dgram: Non-linked UDP protocol
Encapsulate IP Address and port number:
Code:
struct SOCKADDR_IN server;
int port = 8888;
Bzero (&server,sizeof (server));
Server.sin_family=af_inet
SERVER.SIN_ADDR.S_ADDR = Inaddr_any;
Server.sin_port = htons (port);
Comments:
1.bzero (); Used to initialize the struct sockaddr_in
2.sin_family set the network protocol, only the Af_inet
3.sin_addr.s_addr used to set the IP address, Inaddr_any represents the native IP address
4.sin_port used to set the port number
Binding sockets and Struct SOCKADDR_IN
Code:
Bind (sock, struct sockaddr*) &server,sizeof (struct sockaddr));
Comments:
Bind (sock handle, struct sockaddr_in pointer, struct sockaddr_in length);
Turn on listening for client connections:
Code:
struct SOCKADDR_IN temp;
int addresssize;
int client_sock;
while (1)
{
Client_sock=accept (sock, (struct sockaddr_in*) &temp,&addresssize);
}
Send and receive client data:
Char buf[1024];
int Len;
Recv (client_sock,buf,1024,0);
printf ("Client recv:%s\n", buf);
Len=strlen (BUF);
Send (client_sock,buf,len,0);
Linux socket recognition