addr_in *ipv4 = (struct sockaddr_in *)&clientAddr;
addr = &(ipv4->sin_addr);
inet_ntop(AF_INET, addr, ipstr, sizeof(ipstr));
printf("client: %s\n", ipstr);
if (!fork()) {
close(sockfd); /* child doesn't need the listener */
/* Copy Data */
msg = "The server simply displays a message!";
sendSta = send(connFd, msg, strlen(msg), 0);
if (sendSta == -1)
fprintf(stderr, "send fail!");
close(connFd);
exit(0);
}
close(connFd);
}
close(sockfd);
return 0;
}
/**
* Version: 0.2
*
* Description: Add signal
*
*/
#include
#include
#include
#include
#include
#include
#include
#include
#include /* exit declare */
#include /* fork declare */
#define SERVPORT "2349"
void sigchild_handler()
{
while (waitpid(-1, NULL, WNOHANG) > 0);
}
int main(int argc, char *argv[])
{
struct addrinfo hints, *res;
int status;
int sockfd;
int connFd;
/* struct sockaddr_in cliAddr; Only IPv4 */
struct sockaddr_storage clientAddr; /* both IPv4 and IPv6 */
struct sigaction sa;
int sendSta;
char *msg;
if (argc != 2) {
fprintf(stderr, "Usage: Not found Read File");
return 1;
}
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
status = getaddrinfo(NULL, SERVPORT, &hints, &res);
if (status != 0) {
fprintf(stderr, "getaddrinfo, fail!");
return 2;
}
sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
bind(sockfd, res->ai_addr, res->ai_addrlen);
listen(sockfd, 5);
printf("======== Please Wait Client =========\n");
/* struct sigaction notes from POSIX:
*
* (1) Routines stored in sa_handler should take a single int as
* their argument although the POSIX standard does not require this.
* (2) The fields sa_handler and sa_sigaction may overlap, and a conforming
* application should not use both simultaneously.
*/
sa.sa_handler = sigchild_handler;
sigemptyset(&sa.sa_mask); /* Additional set of signals to be blocked */
/* during execution of signal-catching function. */
sa.sa_flags = SA_RESTART; /* Special flags to affect behavior of signal */
/* SA_RESTART 0x10000000 // Restart syscall on signal return */
if (sigaction(SIGCHLD, &sa, NULL) == -1) { /* SIGCHLD 20 // to parent on child stop or exit */
fprintf(stderr, "sigaction fail!");
exit(3);
}
while(1) { // loop forever!
char ipstr[INET_ADDRSTRLEN];
void *addr;
int len = sizeof(clientAddr);
connFd = accept(sockfd, (struct sockaddr *)&clientAddr, &len);
/* View Client IP */
struct sockaddr_in *ipv4 = (struct sockaddr_in *)&clientAddr;
addr = &(ipv4->sin_addr);
inet_ntop(AF_INET, addr, ipstr, sizeof(ipstr));
printf("client: %s\n", ipstr);
if (!fork()) {
close(sockfd); /* child doesn't need the listener */
/* Copy Data */
msg = "The server simply displays a message!";
sendSta = send(connFd, msg, strlen(msg), 0);
if (sendSta == -1)
fprintf(stderr, "send fail!");
close(connFd);
exit(0);
}
close(connFd);
}
close(sockfd);
return 0;
}
End.
摘自 xiaobin_HLJ80的专栏