服务器
#include<stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "string.h"
#include "stdlib.h"
#include "unistd.h"
#define IP "127.0.0.1"
#define PORT 6666
int main()
{
int list_fb=0,Data_fb=0,ret=0,len=0;
char buf[512]={0};
struct sockaddr_in list_buf,Data_buf;
//建立监听套接字
list_fb=socket(AF_INET,SOCK_STREAM,0);
//绑定IP地址和端口号
list_buf.sin_family=AF_INET;
list_buf.sin_port=htons(PORT);
list_buf.sin_addr.s_addr=inet_addr(IP);
ret=bind(list_fb,(struct sockaddr *)&list_buf,sizeof(list_buf));
if(ret == -1)
{
perror("bind");
return -1;
}
printf("绑定成功!\n");
//开始监听
ret=listen(list_fb,2);
if(ret == -1)
{
perror("listen");
return -1;
}
printf("监听成功!\n");
//等待链接
len=sizeof(Data_buf);
Data_fb = accept(list_fb,(struct sockaddr *)&Data_buf,&len);
printf("与%s链接成功!\n",inet_ntoa(Data_buf.sin_addr));
while(1)
{
//接受数据
memset(buf,0,512);
recv(Data_fb,buf,512,0);
printf("收到的数据>>%s\n",buf);
//发送
memset(buf,0,512);
printf("要发送的数据>>\n");
fgets(buf,512,stdin);
send(Data_fb,buf,strlen(buf),0);
}
close(Data_fb);
close(list_fb);
客户端
#include<stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "string.h"
#include "stdlib.h"
#include "unistd.h"
#define IP "127.0.0.1"
#define PORT 6666
int main()
{
int list_fb=0,Data_fb=0,ret=0,len=0;
char buf[512]={0};
struct sockaddr_in MY_buf,Data_buf;
len=sizeof(Data_buf);
//建立监听套接字
Data_fb=socket(AF_INET,SOCK_STREAM,0);
//绑定IP地址和端口号
Data_buf.sin_family=AF_INET;
Data_buf.sin_port=htons(PORT);
Data_buf.sin_addr.s_addr=inet_addr(IP);
//建立链接
ret=connect(Data_fb,(struct sockaddr *)&Data_buf,len);
if(ret == -1)
{
perror("connect");
return -2;
}
printf("链接成功!\n");
while(1)
{
//发送
memset(buf,0,512);
printf("要发送的数据>>\n");
fgets(buf,512,stdin);
//send(Data_fb,buf,strlen(buf),0);
write(Data_fb,buf,strlen(buf));
//接受数据
memset(buf,0,512);
//recv(Data_fb,buf,512,0);
read(Data_fb,buf,512);
printf("收到的数据>>%s\n",buf);
}
close(Data_fb);
先运行服务器再运行客户端