服务器:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define ERRLINE(msg) do{fprintf(stderr,"line:%d\n",__LINE__);perror("msg");}while(0);
#define IP "192.168.0.7"
int main(int argc, const char *argv[])
{
//1.socket创建套接字
int fd = socket(AF_INET,SOCK_STREAM,0);
if(fd<0)
{
ERRLINE("socket");
return -1;
}
//2.bind 连接ip和端口号
struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(7777);
sin.sin_addr.s_addr = inet_addr(IP);
if(bind(fd,(struct sockaddr *)&sin,sizeof(sin))<0)
{
ERRLINE("bind");
return -1;
}
//3.listen 建立监听机制
if(listen(fd,128)<0)
{
ERRLINE("listen");
return -1;
}
//4.accept 从套接字创建的文件描述符里获取信息,生成新的文件描述符
struct sockaddr_in cin;
socklen_t len = 0;
int newfd = accept(fd,(struct sockaddr*)&cin,&len);
if(newfd<0)
{
ERRLINE("accept");
return -1;
}
//5.recv 接受客户端信息
char buf[1024]={0};
ssize_t ret = 0;
while(1)
{
ret = recv(newfd,buf,sizeof(buf),0);
if(ret<0)
{
ERRLINE("recv");
return -1;
}
else if(ret==0)
{
printf("客户端已关闭\n");
break;
}
printf("[%s]:%s\n",inet_ntoa(cin.sin_addr),buf);
//6.send 发送信息给客户端
strcat(buf,"thanks");
if(send(newfd,buf,sizeof(buf),0)<0)
{
ERRLINE("send");
return -1;
}
}
close(newfd);
close(fd);
return 0;
}
客户端:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define ERRLINE(msg) do{fprintf(stderr,"line:%d\n",__LINE__);perror("msg");}while(0);
#define IP "192.168.0.7"
int main(int argc, const char *argv[])
{
//1.socket创建套接字
int fd = socket(AF_INET,SOCK_STREAM,0);
if(fd<0)
{
ERRLINE("socket");
return -1;
}
#if 0
//2.bind 连接ip和端口号
struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(7777);
sin.sin_addr.s_addr = inet_addr(IP);
if(bind(fd,(struct sockaddr *)&sin,sizeof(sin))<0)
{
ERRLINE("bind");
return -1;
}
//3.listen 建立监听机制
if(listen(fd,128)<0)
{
ERRLINE("listen");
return -1;
}
//4.accept 从套接字创建的文件描述符里获取信息,生成新的文件描述符
struct sockaddr_in cin;
socklen_t len = 0;
int newfd = accept(fd,(struct sockaddr*)&cin,&len);
if(newfd<0)
{
ERRLINE("accept");
return -1;
}
#endif
//2.connect连接服务器
struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(7777);
sin.sin_addr.s_addr = inet_addr(IP);
if(connect(fd,(struct sockaddr*)&sin,sizeof(sin))<0)
{
ERRLINE("connect");
return -1;
}
char buf[1024]={0};
ssize_t ret = 0;
while(1)
{
//3.send 发送信息给客户端
bzero(buf,sizeof(buf));
printf("请发送信息到服务器:");
fgets(buf,sizeof(buf),stdin);
buf[strlen(buf)-1]='\0';
if(send(fd,buf,sizeof(buf),0)<0)
{
ERRLINE("send");
return -1;
}
//4.recv 接受客户端信息
ret = recv(fd,buf,sizeof(buf),0);
if(ret<0)
{
ERRLINE("recv");
return -1;
}
else if(ret==0)
{
printf("服务器已关闭\n");
break;
}
printf("%s\n",buf);
// strcat(buf,"thanks");
}
// close(newfd);
close(fd);
return 0;
}