linux 网络编程之最简单的tcp通信服务端

编写一个最为简单的tcp通信服务端。代码如下:

#include <iostream>
#include <cstring>
using namespace std;

#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <unistd.h>


int main()
{
/*创建socket*/
        int sd = socket(AF_INET, SOCK_STREAM, 0);
        if (sd == -1)
        {
                cout << "socket creat error" << endl;
                cout << errno << ":" << strerror(errno) << endl;exit(-1);
        }

/*定义地址*/
        struct sockaddr_in addr = {0};
        addr.sin_family = AF_INET;
        addr.sin_port = htons(12222);
        inet_aton("192.168.56.11", &addr.sin_addr);

/*绑定地址*/
        int bd_ret = bind(sd, (struct sockaddr*)&addr, sizeof(addr));
        if (bd_ret != 0)
        {
                cout << "socket bind error" << endl;
                cout << errno << ":" << strerror(errno) << endl;exit(-1);
        }

/*监听客户端连接*/
        int ls_ret = listen(sd, 5);
        if (ls_ret != 0)
        {
                cout << "socket listen error" << endl;
                cout << errno << ":" << strerror(errno) << endl;exit(-1);
        } 

/*获取连接*/
        struct sockaddr_in cli_addr = {0};
        unsigned int addr_len = sizeof(cli_addr);
        int sd_cli = accept(sd, (struct sockaddr*)&cli_addr, &addr_len);
        if (sd_cli == -1)
        {
                cout << "socket accept error" << endl;
                cout << errno << ":" << strerror(errno) << endl;exit(-1);
        }

/*通信*/
        char recv_buf[100] = {0};
        int recv_count = recv(sd_cli, recv_buf, 55, 0);
        if (recv_count <= 0)
        {
                cout << "socket recv error" << endl;
                cout << errno << ":" << strerror(errno) << endl;exit(-1);
        }

        cout << "Client information" << endl;
        cout << "cli ip: " << inet_ntoa(cli_addr.sin_addr) << endl;
        cout << "cli port: " << ntohs(cli_addr.sin_port) << endl;
        cout << "recv buf: " << recv_buf << endl;

/*退出*/
        close(sd_cli);
        close(sd);
        return 0;
}


郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。