客户端
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#define ERR_MSG(msg) do{\
fprintf(stdout,"line----->%d\n",__LINE__);\
perror(msg);\
}while(0)
int main(int argc,const char * argv[])
{
//1.socket
int cfd = socket(AF_INET,SOCK_STREAM,0);
if(cfd < 0)
{
ERR_MSG("socket");
return -1;
}
//2.不bind
struct sockaddr_in sd;
sd.sin_family = AF_INET;
sd.sin_port = htons(6666);
sd.sin_addr.s_addr = inet_addr(argv[1]);
//3.connect
if(connect(cfd,(struct sockaddr *)&sd,sizeof(sd)) <0 )
{
ERR_MSG("connect");
return -1;
}
//4.send
while(1)
{
char buf[128]="";
fgets(buf,sizeof(buf),stdin);
int send_return = send(cfd,buf,sizeof(buf),0);
if(send_return <0)
{
ERR_MSG("send");
return -1;
}
bzero(buf,sizeof(buf));
int recv_return = recv(cfd,buf,sizeof(buf),0);
if(recv_return == 0)
{
printf("服务端挂了\n");
break;
}
else if(recv_return > 0)
{
printf("接收服务端的数据是:%s\n",buf);
}
else if(recv_return <0 )
{
ERR_MSG("recv");
return -1;
}
}
close(cfd);
return 0;
}
服务端
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/socket.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define ERR_MSG(msg) do{\
fprintf(stderr,"line-->%d\n",__LINE__);\
perror(msg);\
}while(0)
int main(int argc,const char * argv[])
{
//1.创建套接字流,ipv4
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;
}
struct sockaddr_in sa;
sa.sin_family = AF_INET;
sa.sin_port = htons(6666);
sa.sin_addr.s_addr = inet_addr(argv[1]);
//2.bind[绑定端口和ip]
if(bind(sfd,(struct sockaddr *)&sa,sizeof(sa)) < 0)
{
ERR_MSG("bind");
return -1;
}
//3.listen[讲通信改为监听]
if(listen(sfd,128) < 0)
{
ERR_MSG("listen");
return -1;
}
printf("*************************\n");
//4.accept[客户端连接]
struct sockaddr_in cls;
socklen_t addrlen = sizeof(cls);
int cfd = accept(sfd,(struct sockaddr *)&cls,&addrlen);
if(cfd <0 )
{
ERR_MSG("accept");
return -1;
}
//5.recv接收客户端信息
ssize_t s;
char buf[128]="";
while(1)
{
bzero(buf,sizeof(buf));
s = recv(cfd,buf,sizeof(buf),0);
if(s == 0)
{
printf("客户端挂了\n");
break;
}
else if(s > 0)
{
printf("接收的消息是:%s\n",buf);
}
else if(s < 0)
{
ERR_MSG("recv");
return -1;
}
//6.给客户端发送消息send
int send_return = send(cfd,buf,sizeof(buf),0);
if(send_return < 0)
{
ERR_MSG("send");
return -1;
}
}
close(sfd);
close(cfd);
return 0;
}