下面一段代码是创建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
原文:http://www.cnblogs.com/clyskyblue/p/3578709.html