1、创建一个简单的TCP服务器
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#define ERR_MSG(msg) do{\
fprintf(stderr,"__%d__\n",__LINE__);\
perror(msg);\
}while(0)
typedef struct {
ssize_t res;
char buf[128];
}DataBag;
int main(int argc, const char *argv[])
{
if(argc<3){
fprintf(stderr,"请传参:%s ip port\n",argv[0]);
return -1;
}
//创建套接字
int sfd=socket(AF_INET,SOCK_STREAM,0);
if(sfd<0){
ERR_MSG("socket");
return -1;
}
printf("socket success\n");
//填充地址结构体
struct sockaddr_in sin;
sin.sin_family=AF_INET;
sin.sin_port=htons(atoi(argv[2]));
sin.sin_addr.s_addr=inet_addr(argv[1]);
//bind绑定ip与端口号
if(bind(sfd,(struct sockaddr *)&sin,sizeof(sin))<0){
ERR_MSG("bind");
return -1;
}
printf("bind success\n");
//设置监听状态
if(listen(sfd,10)<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;
}
printf("accept success\n");
printf("客户端ip:%s 客户端port:%d\n",\
inet_ntoa(cin.sin_addr),ntohs(cin.sin_port));
//功能
DataBag bag;
while(1){
memset(&bag,0,sizeof(bag));
bag.res=recv(newfd,bag.buf,sizeof(bag.buf),0);
if(bag.res<0){
ERR_MSG("recv");
break;
}else if(0==bag.res){
printf("[ %s : %d ]客户端退出\n",\
inet_ntoa(cin.sin_addr),ntohs(cin.sin_port));
break;
}
printf("%s\n",bag.buf);
}
close(sfd);
close(newfd);
return 0;
}
2、创建一个简单的TCP客户端
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#define ERR_MSG(msg) do{\
fprintf(stderr,"__%d__\n",__LINE__);\
perror(msg);\
}while(0)
typedef struct {
ssize_t res;
char buf[128];
}DataBag;
int main(int argc, const char *argv[])
{
if(argc<3){
fprintf(stderr,"请传参:%s ip port\n",argv[0]);
return -1;
}
//创建套接字
int cfd=socket(AF_INET,SOCK_STREAM,0);
if(cfd<0){
ERR_MSG("socket");
return -1;
}
printf("socket success\n");
//填充地址结构体
struct sockaddr_in sin;
sin.sin_family=AF_INET;
sin.sin_port=htons(atoi(argv[2]));
sin.sin_addr.s_addr=inet_addr(argv[1]);
//连接服务器
if(connect(cfd,(struct sockaddr *)&sin,sizeof(sin))<0){
ERR_MSG("connect");
return -1;
}
printf("connect success\n");
//功能
DataBag bag;
while(1){
memset(&bag,0,sizeof(bag));
printf("请输入>>>");
fgets(bag.buf,sizeof(bag.buf),stdin);
bag.buf[strlen(bag.buf)-1]=0;
if(strcasecmp(bag.buf,"quit")==0)
break;
if(send(cfd,bag.buf,sizeof(bag.buf),0)<0){
ERR_MSG("send");
break;
}
}
close(cfd);
return 0;
}
测试: