c++ 创建 socket server

下面一段代码是创建socket server的代码片段:

需要引用的库包括:

1
2
3
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
    int ss = -1;
ss = socket(AF_INET,SOCK_STREAM,0); //获得句柄
if(ss < 0){
    fprintf(stderr,"socket create error\n");
    return false;
}
server_fd = ss;
sockaddr_in server_addr;
server_addr.sin_family = AF_INET; //协议类型
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);//ip地址
server_addr.sin_port = htons(server_port);//端口号
int ret =  bind(ss,(sockaddr*)&server_addr,sizeof(server_addr)); //绑定地址与端口
if(ret < 0){
    fprintf(stderr,"error in bind\n");
    return false;
}
ret = listen(ss,max_wait_num);//开始监听
if(ret < 0){
    fprintf(stderr,"error in listen\n" );
    return false;
}

  

1
2
int sc = accept(ss,(sockaddr*)&from,&len);
fprintf(stderr, "get one connection:[%d]\n", sc);

  

c++ 创建 socket server,布布扣,bubuko.com

c++ 创建 socket server

上一篇:eclipse+MinGW(C++11)


下一篇:macbook air m1上传文件到github