服务端
#include
#include
#include
#include
#include
#include
#include
//宏定义
#define ERR_MSG(msg) do{fprintf(stderr,"line:%d\n",__LINE__);perror(msg);}while(0)
#define PORT 1151
#define IP "192.168.0.117"
int main(int argc, const char *argv[])
{
//创建流式套接字
int sfd = socket(AF_INET,SOCK_STREAM,0);
if(sfd < 0)
{
ERR_MSG("socket");
return -1;
}
//端口重复使用
int reuse = 1;
if(setsockopt(sfd,SOL_SOCKET,SO_REUSEADDR,&reuse,sizeof(reuse))<0)
{
ERR_MSG("setsockopt");
return -1;
}
printf("允许重复使用");
//填充服务器地址信息结构体
struct sockaddr_in sin;
sin.sin_family = AF_INET; //填充AF_INET
sin.sin_port = htons(PORT); //端口号的网络字节序
sin.sin_addr.s_addr = inet_addr(IP); //IP,本机的IP
//绑定。功能:将服务端的IP地址和端口号绑定到服务器的套接字文件中
if(bind(sfd,(struct sockaddr *)&sin,sizeof(sin)) < 0)
{
ERR_MSG("bind");
return -1;
}
//输出验证
printf("bind is success __%d__\n",__LINE__);
//被动监听状态
if(listen(sfd,128) < 0)
{
ERR_MSG("listen");
return -1;
}
//输出验证
printf("listen is success __%d__\n",__LINE__);
//存储连接成功的客户端地址
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;
}
//输出验证
printf("连接成功[%s:%d]newfd = %d __%d__\n",inet_ntoa(cin.sin_addr),ntohs(cin.sin_port),newfd,__LINE__);
char buf[1024] = "";//定义一个数组
size_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(res == 0)
{
printf("客户端已下线[%s:%d]newfd = %d __%d__\n",inet_ntoa(cin.sin_addr),ntohs(cin.sin_port),newfd,__LINE__);
break;
}
printf("连接成功[%s:%d]newfd = %d __%d__\n",inet_ntoa(cin.sin_addr),ntohs(cin.sin_port),newfd,__LINE__);
//发送
strcat(buf,"return word");
if(send(newfd,buf,sizeof(buf),0) <0)
{
ERR_MSG("send");
return -1;
}
printf("发送成功\n");
}
//关闭
close(newfd);
close(sfd);
return 0;
}
客户端
#include
#include
#include
#include
#include
#include
#include
#define ERR_MSG(msg) do{fprintf(stderr,"line:%d\n",__LINE__);perror(msg);}while(0)
#define IP "192.168.0.117"
#define PORT 1151
int main(int argc, const char *argv[])
{
//1.创建流式套接字
int cfd = socket(AF_INET,SOCK_STREAM,0);
if(cfd<0)
{
ERR_MSG("socket");
return -1;
}
//2.填充服务器地址信息
struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(PORT);//端口号的网络字节序1024--49151
sin.sin_addr.s_addr= inet_addr(IP);//IP 本机IP ifconfig
//3.非绑定
if(connect(cfd,(struct sockaddr *)&sin,sizeof(sin)) < 0)
{
ERR_MSG("connect");
return -1;
}
printf("连接成功\n");
char buf[1024] = "";
size_t res = 0;
while(1)
{
bzero(buf,sizeof(buf));
printf("Input>>>>");
fgets(buf,sizeof(buf),stdin);
buf[strlen(buf)-1] = '\0';
//send
if(send(cfd,buf,sizeof(buf),0)<0)
{
ERR_MSG("send");
return -1;
}
printf("send success\n");
bzero(buf,sizeof(buf));//清零
//5.接收
res = recv(cfd,buf,sizeof(buf),0);
if(res < 0)
{
ERR_MSG("recv");
return -1;
}
else if(res == 0)
{
printf("服务器下线\n");
break;
}
printf(" : %s__%d__\n",buf,__LINE__);
}
//7.关闭文件描述符
close(cfd);
return 0;
}
运行结果