File: client-server.c

package info (click to toggle)
dmtcp 2.6.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 6,496 kB
  • sloc: cpp: 33,592; ansic: 28,099; sh: 6,735; makefile: 1,950; perl: 1,690; python: 1,241; asm: 138; java: 13
file content (58 lines) | stat: -rw-r--r-- 1,634 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#define _DEFAULT_SOURCE
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>

#include <stdio.h>

int main(int argc, char *argv[]) {
  int port = (argc == 2 ? atoi(argv[1]) : 6500);
  struct sockaddr_in sockaddr;
  int listener_sd, rc;
  pid_t pid;

  memset(&sockaddr, 0, sizeof(sockaddr));
  sockaddr.sin_family = AF_INET;
  inet_aton("127.0.0.1", &sockaddr.sin_addr);
  // sockaddr.sin_addr.s_addr = INADDR_LOOPBACK;
  sockaddr.sin_port = htons(port);

  listener_sd = socket(AF_INET, SOCK_STREAM, 0);
  do {
    sockaddr.sin_port = htons(ntohs(sockaddr.sin_port)+1);
    rc = bind(listener_sd, (struct sockaddr *)&sockaddr, sizeof(sockaddr));
  } while (rc == -1 && errno == EADDRINUSE);
  if (rc == -1)
    perror("bind");
  listen(listener_sd, 5);

  pid = fork();
  if (pid) { /* if parent process */
    int sd;
    int i = 0;
    char byte;
    close(listener_sd);
    sd = socket(AF_INET, SOCK_STREAM, 0); /* create connection socket */
    connect(sd, (struct sockaddr *)&sockaddr, sizeof(sockaddr));
    while (1) { /* client writes and then reads */
      if (i++ % 1000 == 0) {printf("."); fflush(stdout);}
      if (i % 50000 == 0) printf("\n");
      while (write(sd, &byte, 1) != 1) ;
      while (read(sd, &byte, 1) != 1);
    }
  } else { /* else child process */
    int sd;
    char byte;
    sd = accept(listener_sd, NULL, NULL);
    while (1) { /* server reads and then writes */
      while (read(sd, &byte, 1) != 1);
      while (write(sd, &byte, 1) != 1) ;
    }
  }
}