c++ 创建 socket server

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

需要引用的库包括:

#include <sys/types.h>

#include <sys/socket.h>

#include <arpa/inet.h>

  

        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;

	}

  

int sc = accept(ss,(sockaddr*)&from,&len);

fprintf(stderr, "get one connection:[%d]\n", sc);

  

你可能感兴趣的:(socket)