A very good Socket program source code (server side)

zhaozj2021-02-16  106

/ *

Servidor de escucha EN un puerto.

Listening Server ON A Port.

BY:

POR:

Oscar Medina Duarte

IS111936@mail.udlap.mx

Linux> GCC Server1.c

Solaris> cc server1.c -lxnet -lnsl -lsocket

* /

#include

#include

#include

#include

#define numerodepuerto 6666;

EXTERN INT APAGAR = 0;

Void SignalHD (Int Senal);

Void Protocolo_Control (int);

MAIN () {

Struct sockaddr_in sin, fsin

Int S, SSOCK, ALEN;

CHAR * RCHS;

sin.sin_family = af_INet;

sin.sin_addr.s_addr = htonl (INADDR_Any);

Sin.sin_port = numerodepuerto;

IF ((S = Socket, Sock_Stream, 0)) <0) {

PERROR ("Cant Create Socket");

Exit (1);

}

IF (Bind (S. (Struct SockAddr *) & Sin, SIZEOF SIN <0) {

Perror ("Cant Assign Addres";

EXIT (2);

}

IF (Listen (S, 5) <0) {

Perror ("Cant Turn to Listening Mode";

EXIT (3);

}

Signal (SIGCHLD, SIG_IGN);

Signal (SIGINT, SIGNALHD);

While (1) {

IF (apagar) {

Close (s);

exit (0);

}

Alen = Sizeof (fsin);

IF ((SSOCK = Accept (S, Struct SockAddr *) & fsin, & alen) <0) {

IF (errno == eintr) Continue;

PERROR ("Accept Failed");

EXIT (4);

}

RCHS = (char *) INET_NTOA (fsin.sin_addr);

Printf ("/ NCONEXION from:% S / N", RCHS);

Switch (fork ()) {

Case -1: {

Perror ("forking error");

EXIT (5);

}

Case 0: {

Close (s);

Protocolo_Control (SSOCK);

exit (0);

}

DEFAULT: {

Close (SSOCK);

Break;

}

}

}

}

Void protocolo_control (int descriptor) {

Char buf [4096];

INT CC;

CC = Read (Descriptor, BUF, SIZEOF BUF);

IF (cc> 0) {

Printf ("Readed Data: / N% S / N", BUF);

Write (Descriptor, BUF, Strlen (BUF));

}

}

Void SignalHd (INT SENAL) {IF (Senal == Sigint) {

Printf ("... Interrupt ... / N");

Apagar = 1;

}

}

转载请注明原文地址:https://www.9cbs.com/read-10404.html

New Post(0)