zoukankan      html  css  js  c++  java
  • Linux TCP/IP 实例

    //============================================================================
    // Name        : ServerBase.cpp
    // Author      : 
    // Version     :
    // Copyright   : Your copyright notice
    // Description : Hello World in C++, Ansi-style
    //============================================================================
    
    #include <stdio.h>
    #include <stdlib.h>
    #include <errno.h>
    #include <string.h>
    #include <sys/types.h>
    #include <netinet/in.h>
    #include <sys/socket.h>
    #include <sys/wait.h>
    #include <unistd.h> // fork, close
    #include <arpa/inet.h>  // inet_ntoa
    #define SERVPORT 3333    /*服务器监听端口号 */
    #define BACKLOG 10    /* 最大同时连接请求数 */
    int main()
    {
    	printf("Start Listener ");
        int sock_fd,client_fd;    /*sock_fd:监听socket;client_fd:数据传输socket */
        int sin_size;
        struct sockaddr_in my_addr;    /* 本机地址信息 */
        struct sockaddr_in remote_addr;    /* 客户端地址信息 */
        if((sock_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
            perror("socket创建出错!");
            exit(1);
        }
        my_addr.sin_family=AF_INET;
        my_addr.sin_port=htons(SERVPORT);
        my_addr.sin_addr.s_addr = INADDR_ANY;
        bzero(&(my_addr.sin_zero),8);
        if(bind(sock_fd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) == -1) {
            perror("bind出错!");
            exit(1);
        }
        if(listen(sock_fd, BACKLOG) == -1) {
            perror("listen出错!");
            exit(1);
        }
        while(1) {
            sin_size = sizeof(struct sockaddr_in);
            if((client_fd = accept(sock_fd, (struct sockaddr *)&remote_addr, (socklen_t *)&sin_size)) == -1) {
                perror("accept出错");
                continue;
            }
            printf("received a connection from %s
    ", inet_ntoa(remote_addr.sin_addr));
            if(!fork()) {    /* 子进程代码段 */
                if(send(client_fd, "Hello, you are connected!
    ", 26, 0) == -1) {
                    perror("send出错!");
                }
                close(client_fd);
                exit(0);
            }
            close(client_fd);
        }
    }
    


  • 相关阅读:
    Django视图之ORM数据库查询操作API
    Django视图之ORM更改数据库连接——配置MySQL库
    TLPI读书笔记第2章-基本概念2
    TLPI读书笔记第2章-基本概念1
    linux防火墙常用命令
    linux配置yum软件仓库
    linux进程管理
    linux文件权限
    linux用yum安装软件
    linux磁盘划分
  • 原文地址:https://www.cnblogs.com/hzcya1995/p/13318912.html
Copyright © 2011-2022 走看看