Linux下服务端编程

#include <stdio.h>
#include <sys/socket.h>
#include <unistd.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <time.h>

#define SERVER_PORT 20000
#define LEN_LISTEN_QUEUE 10
#define BUFFER_SIZE 255
#define WELCOME_MESSAGE "welcome to connect the server. "

int main(int argc, char **argv)
{
  int server_sockfd, client_sockfd;
  struct sockaddr_in server_addr;
  struct sockaddr_in client_addr;

  printf("the server program!\n");

  if ((server_sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
  {
    printf("create socket error!\n");
    exit(1);
  }

  bzero(&server_addr, sizeof(server_addr));
  server_addr.sin_family = AF_INET;
  server_addr.sin_port = htons(SERVER_PORT);
  server_addr.sin_addr.s_addr = htons(INADDR_ANY);

  if(bind(server_sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0)
  {
    printf("bind to port %d failure!\n", SERVER_PORT);
    exit(1);
  }

  if(listen(server_sockfd, LEN_LISTEN_QUEUE) < 0)
  {
    printf("call listen failure!\n");
    exit(1);
  }

  while(1)
  {
    char buf[BUFFER_SIZE];
    long timestamp;

    socklen_t length = sizeof(client_addr);
    client_sockfd = accept(server_sockfd, (struct sockaddr *)&client_addr, &length);

    if(client_sockfd < 0)
    {
      printf("error comes when call accept!\n");
      break;
    }

    strcpy(buf, WELCOME_MESSAGE);
    printf("from client,IP:%s,Port:%d\n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));

    timestamp = time(NULL);
    strcat(buf, "timestamp in server:");
    strcat(buf, ctime(& timestamp));
    send(client_sockfd, buf, BUFFER_SIZE, 0);
    close(client_sockfd);
  }

  close(server_sockfd);
  return 0;
}

你可能感兴趣的:(linux,职场,服务端编程,休闲)