Information Technology News
Write your own Linux server part two | Write your own Linux server part two |
|
| by David M Williams | |
| Tuesday, 21 August 2007 | |
|
Page 1 of 4
In part one, we presented a real-world story where a Linux server – or daemon – solved a need for an ISP. The code to achieve this was introduced, and annotated. However, we left the best till now – the actual socket handling itself, plus the rc.d script to start the daemon at boot time and kill it at shutdown.
Featured Whitepaper
5 Best Practices for Smartphone Support
int main (int argc, char *argv []) { struct sockaddr_in sin, fsin; struct protoent *ppe; int sock, ssock; int alen; int port = 5000; int qlen = 5; int pid; int fd; char nowtime [26]; char Remote [80]; int connections = 0; FILE *logfp = NULL;
{ printf ("\n%s must be run with super-user privileges.\n", argv [0]); return 0; }
sin.sin_family = AF_INET;
if ((ppe = getprotobyname ("tcp")) == 0)
if ((sock = socket (PF_INET, SOCK_STREAM, ppe->p_proto)) < 0)
if (bind (sock, (struct sockaddr *) &sin, sizeof (sin)) < 0)
if (listen (sock, qlen) < 0)
if ((pid = fork ()) < 0) errexit ("Error setting up server: %s\n", strerror (errno));
if (pid) // Non-zero is parent.
fd = open ("/dev/tty", O_RDWR);
while (1) { alen = sizeof (fsin); ssock = accept (sock, (struct sockaddr *) &fsin, &alen); if (ssock < 0) { if (errno == EINTR) continue; else errexit ("accept: %s\n", strerror (errno)); }
strcpy (Remote, IPtoAddress (fsin.sin_addr)); connections++; if (fork () == 0) { process (ssock, Remote, connections); exit (0); } else close (ssock); } }
|
| < Next story in category | Previous story in the category > |
|---|









