搭建简单的服务器和客户端
服务器
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#define PORT 8888
#define IP "192.168.21.140"
#define ERR_MSG(msg) {printf("line=%d ",__LINE__);perror("msg");}
int main(int argc, const char *argv[])
{
int sfd=socket(AF_INET,SOCK_STREAM,0);//AF_INET选择IPV4,SOCK_STREAM选择TCP,0是默认
if (sfd<0)
{
ERR_MSG("socket");
return -1;
}
struct sockaddr_in sin;
sin.sin_family=AF_INET; //代表选择的是IPV4
sin.sin_port=ntohs(PORT); //端口的网络字节序
sin.sin_addr.s_addr=inet_addr(IP); //IP的网络字节序
if (bind(sfd,(struct sockaddr*)&sin,sizeof(sin))<0)
{
ERR_MSG("bind");
return -1;
}
if (listen(sfd,128)<0)
{
ERR_MSG("listen");
return -1;
}
struct sockaddr *connection_done; //存储已连接的客户端
socklen_t len=sizeof(*connection_done);
int cfd=accept(sfd,connection_done,&len);
if (cfd<0)
{
ERR_MSG("accept");
return -1;
}
printf("客户端已连接\n");
char buf[256]="";
ssize_t res=999;
while(res!=0)
{
res=recv(cfd,buf,128,0);
if (res<0)
{
ERR_MSG("recv");
return -1;
}
printf("%s",buf);
bzero(buf,sizeof(buf));
}
printf("客服端已关闭\n");
close(cfd);
close(sfd);
return 0;
}
客户端
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#define PORT 8888
#define IP "192.168.21.140"
#define ERR_MSG(msg) {printf("line=%d\n",__LINE__);perror("msg");}
int main(int argc, const char *argv[])
{
int sfd=socket(AF_INET,SOCK_STREAM,0);//AF_INET选择IPV4,SOCK_STREAM选择TCP,0是默认
if (sfd<0)
{
ERR_MSG("socket");
return -1;
}
struct sockaddr_in sin;
sin.sin_family=AF_INET; //代表选择的是IPV4
sin.sin_port=ntohs(PORT); //端口的网络字节序
sin.sin_addr.s_addr=inet_addr(IP); //IP的网络字节序
if( connect(sfd,(struct sockaddr *)&sin,sizeof(sin))!=0)
{
ERR_MSG("connect");
return -1;
}
printf("链接服务器成功\n");
char buf[256]="1";
ssize_t res=999;
while(res!=0)
{
fgets(buf,128,stdin);
if (strcmp(buf,"quit")==0)
{
return -1;
}
send(sfd,buf,128,0);
if (res<=0)
{
ERR_MSG("recv");
return -1;
}
bzero(buf,sizeof(buf));
}
close(sfd);
return 0;
}