搭建一个服务器
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
//打印错误信息宏函数
#define ERR_MSG(msg) do{\
fprintf(stderr,"__%d__",__LINE__);\
perror(msg);\
}while(0)
#define PORT 8888 //1024~49151
#define IP "192.168.31.107" //本机IP ifconfig查看
void* wri_send(void*arg)
{
pthread_detach(pthread_self());
char buf[128]="";
ssize_t res;
int newfd=*((int*)arg);
while(1)
{
printf("请输入要传输的:\n");
fgets(buf,sizeof(buf),stdin);
res=send(newfd,buf,strlen(buf),0);
if(res<0)
{
ERR_MSG("send");
return NULL;
}
}
}
int main(int argc, const char *argv[])
{
//创建流式套接字
int sfd=socket(AF_INET,SOCK_STREAM,0);
if(sfd<0)
{
ERR_MSG("socket");
return -1;
}
printf("create socket success\n");
//填充地址信息结构体,真是的地址信息结构体与协议族相关
//AF_INET,所以详情请看man 7ip
struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(PORT); //网络字节序端口号
sin.sin_addr.s_addr = inet_addr(IP) ; //网络字节序的IP地址
//将地址信息结构体绑定到套接字上
if(bind(sfd,(struct sockaddr*)&sin,sizeof(sin))<0)
{
ERR_MSG("bind");
return -1;
}
printf("bing success\n");
//将套接字设置为被动监听状态
if(listen(sfd,128)<0)
{
ERR_MSG("listen");
return -1;
}
printf("listen success\n");
struct sockaddr_in cin;
socklen_t addrlen = sizeof(cin);
//从已完成连接的队列头中,取出一个客户端的信息,创建生成一个新的套接字文件描述符
//该文件描述符才是与客户端通信的文件描述符
int newfd = accept(sfd,(struct sockaddr*)&cin,&addrlen);
if(newfd < 0)
{
ERR_MSG("accept");
return -1;
}
//网络字节序的IP-->点分十进制,网络字节序的port-->本机字节序
printf("[%s : %d] newfd =%d\n",inet_ntoa(cin.sin_addr),ntohs(cin.sin_port),newfd);
pthread_t tid;
if(pthread_create(&tid,NULL,wri_send,(void*)&newfd)<0)
{
ERR_MSG("pthread_create");
return -1;
}
char buf[128]="";
ssize_t res=0;
while(1)
{
bzero(buf,sizeof(buf));
//循环接收
res=recv(newfd,buf,sizeof(buf),0);
if(res<0)
{
ERR_MSG("recv");
return -1;
}
else if(0==res)
{
printf("[%s : %d] newfd =%d客户端退出\n",inet_ntoa(cin.sin_addr),ntohs(cin.sin_port),newfd);
break;
}
printf("[%s : %d] newfd =%d:%s\n",inet_ntoa(cin.sin_addr),ntohs(cin.sin_port),newfd,buf);
}
close(sfd);
close(newfd);
return 0;
}