#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <string.h>
#include <unistd.h>
#define IP "192.168.8.112"
#define PORT 8888
#define ERR_MSG(msg) do{\
fprintf(stderr,"__%d__:",__LINE__);\
perror(msg);\
}while(0)
int main(int argc, const char *argv[])
{
int sfd=socket(AF_INET,SOCK_STREAM,0);
int reuse=1;
if(setsockopt(sfd,SOL_SOCKET,SO_REUSEADDR,&reuse,sizeof(reuse))<0){
ERR_MSG("setsockopt");
return -1;
}
printf("允许端口快速重用\n");
struct sockaddr_in sin;
sin.sin_family=AF_INET;
sin.sin_port=htons(PORT);
sin.sin_addr.s_addr=inet_addr(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;
}
printf("服务器监听成功\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("newfd=%d 连接成功\n",newfd);
ssize_t res=0;
char buf[128]="";
size_t len=sizeof(buf);
char cuf[128]="";
while(1){
bzero(buf,sizeof(buf));
res=recv(newfd,buf,len,0);
if(res<0){
ERR_MSG("recv");
return -1;
}else if(0==res){
printf("newfd=%d 客户端关闭\n",newfd);
break;
}
printf("res:%ld nemfd:%d:%s\n",res,newfd,buf);
printf("请输入\n");
bzero(cuf,sizeof(cuf));
scanf("%s",cuf);
if(send(newfd,cuf,sizeof(cuf),0)<0){
ERR_MSG("send");
return -1;
}
}
close(newfd);
close(sfd);
return 0;
}
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <string.h>
#include <unistd.h>
#define ERR_MSG(msg) do{\
fprintf(stderr, "__%d__:", __LINE__);\
perror(msg);\
}while(0)
#define SER_PORT 8888
#define SER_IP "192.168.8.112"
int main(int argc, const char *argv[])
{
//创建流式套接字
int sfd = socket(AF_INET, SOCK_STREAM, 0);
if(sfd < 0)
{
ERR_MSG("socket");
return -1;
}
//填充服务器的地址信息结构体.
struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(SER_PORT);
sin.sin_addr.s_addr = inet_addr(SER_IP);
//连接服务器
if(connect(sfd,(struct sockaddr*)&sin,sizeof(sin))<0){
ERR_MSG("connect");
return -1;
}
printf("connect success\n");
char buf[128]="";
char cuf[128]="";
ssize_t res;
while(1){
bzero(buf,sizeof(buf));
printf("请输入:");
fgets(buf,sizeof(buf),stdin);
buf[strlen(buf)-1]=0;
if(send(sfd,buf,sizeof(buf),0)<0){
if(res<0){
ERR_MSG("recv");
return -1;
}
printf("success\n");
}
bzero(cuf,sizeof(cuf));
res=recv(sfd,cuf,sizeof(cuf),0);
if(res<0){
ERR_MSG("recv");
return -1;
}else if(0==res){
printf("服务器断开连接\n");
break;
}
printf(":%s\n",cuf);
}
close(sfd);
return 0;
}