#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <string.h>
#include <unistd.h>
#define MSG_ERR(msg) do{\
fprintf(stderr,"line:%d",__LINE__);\
perror(msg);\
}while(0)
#define PORT 8888 //1024~49151
#define IP "192.168.52.176" //ifconfig查看自己的IP
int main(int argc, const char *argv[])
{
//创建流式(TCP)套接字
int sfd = socket(AF_INET,SOCK_STREAM,0);
if(sfd<0)
{
MSG_ERR("socket");
return -1;
}
//填充服务器的IP和端口到地址信息结构体上
//地址信息结构体根据地址族指定 man 7 IP
struct sockaddr_in sin;
sin.sin_family = AF_INET;//必须填AF_INET
sin.sin_port = htons(PORT);//网络字节序的端口号1024~49151
sin.sin_addr.s_addr = inet_addr(IP);//网络字节序的IP地址
//将服务器的IP和端口绑定到套接字上;必须绑定
if(bind(sfd,(struct sockaddr*)&sin,sizeof(sin))<0)
{
MSG_ERR("bind");
return -1;
}
printf("bind success\n");
//将套接字设置为被动监听状态
if(listen(sfd,10)<0)
{
MSG_ERR("listen");
return -1;
}
printf("listen success\n");
//获取完成连接的客户信息,生成一个新的文件描述符
int newfd=accept(sfd,NULL,NULL);
if(newfd<0)
{
MSG_ERR("newfd");
return -1;
}
printf("newfd=%d\n",newfd);
char buf[128]="";
ssize_t ret=0;
while(1)
{
bzero(buf,sizeof(buf));
//循环接收数据,阻塞方式接收
ret=recv(newfd,buf,sizeof(buf),0);
if(ret<0)
{
MSG_ERR("recv");
return -1;
}
else if(ret==0)
{
printf("newfd=%d 对应的客户端退出\n",newfd);
break;
}
printf("ret=%ld:buf=%s\n",ret,buf);
}
close(newfd);
close(sfd);
return 0;
}
ubuntu@ubuntu:01_1019$ gcc 02_tcpser.c
ubuntu@ubuntu:01_1019$ ./a.out
bind success
listen success
newfd=4
ret=5:buf=hahah
ret=13:buf=nicetomeetyou
newfd=4 对应的客户端退出