One, in the simplest of the most simple back-end client/server programs, a client is a process that only initiates a connection, and a slight modification allows a client to initiate multiple connections and then send data using only one of the connections.
First come to know a function getsockname
#include <sys/socket.h>
int getsockname (int sockfd, struct sockaddr *addr, socklen_t *addrlen);
Using this function, you can get the address information of a connection sockfd, such as an IP address and port, which can help us determine how many connections have been initiated.
We assume that a client initiated 5 connections, as shown in the following figure:
At this point, according to the previous Fork program, the server side will generate 5 child processes to service it.
The modified client program is as follows:
/************************************************************************* > File name:echoser.c > Author: Simba > Mail:dameng34@163.com > Created time:fri Mar 2013 06:15:27 PM CST *************************** /#include <stdio.h> #include <sys/types.h> #include < sys/socket.h> #include <unistd.h> #include <stdlib.h> #include <errno.h> #include <arpa/inet.h
> #include <netinet/in.h> #include <string.h> #include "read_write.h" #define ERR_EXIT (m) \ Do {\ Perror (m); \ exit (exit_failure);
\} while (0) void do_echocli (int sock) {char sendbuf[1024] = {0};
Char recvbuf[1024] = {0};
while (Fgets (sendbuf, sizeof (SENDBUF), stdin)!= NULL) {writen (sock, SendBuf, strlen (SENDBUF)); int ret = ReadLine (sock, Recvbuf, sizeof (RECVBUF)); Read by row if (ret = 1) err_eXIT ("read error");
else if (ret = 0)//server shuts down {printf ("Server close\n");
Break
} fputs (Recvbuf, stdout);
memset (sendbuf, 0, sizeof (SENDBUF));
memset (recvbuf, 0, sizeof (RECVBUF));
Close (sock);
int main (void) {int sock[5];
int i; for (i = 0; i < 5; i++) {if ((sock[i] = socket (pf_inet, Sock_stream, ipproto_tcp)) < 0)//
LISTENFD = socket (af_inet, sock_stream, 0) err_exit ("Socket error");
struct sockaddr_in servaddr;
memset (&servaddr, 0, sizeof (SERVADDR));
servaddr.sin_family = af_inet;
Servaddr.sin_port = htons (5188);
SERVADDR.SIN_ADDR.S_ADDR = inet_addr ("127.0.0.1"); /* Inet_aton ("127.0.0.1", &servaddr.sin_addr); */if (connect (sock[i), (struct sockaddr *) &servaddr, sizeof (SERVADDR)) < 0) Err_exit ("Con
Nect error ");struct sockaddr_in localaddr;
socklen_t Addrlen = sizeof (LOCALADDR); if (GetSockName (sock[i), (struct sockaddr *) &localaddr, &addrlen) < 0) err_exit ("GetSockName error"
); /* Getpeername () Gets the address of the peer/printf ("Local ip=%s port=%d\n", Inet_ntoa (LOCALADDR.SIN_ADDR), Ntohs (lo
Caladdr.sin_port)); /* A process can also initiate multiple socket connections, because each port number is different * * DO_ECHOCLI (sock[0]);
Initiates 5 socket connections, but communicates with only the first set of interfaces return 0; }