服务器段
#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<netinet/ip.h>
#include<arpa/inet.h>
#include<unistd.h>
#include<stdlib.h>
int main(int argc, char const *argv[])
{
if(argc != 3)
{
printf("please input %s <ip> <port>\n",argv[0]);
}
//1. 创建套接字 socket
int sockfd,acceptfd;
sockfd = socket(AF_INET,SOCK_STREAM,0);
if(sockfd < 0)
{
perror("socket err");
return -1;
}
printf("socket ok %d\n",sockfd);
//填充ipv4的通信结构体
struct sockaddr_in serveraddr;
serveraddr.sin_family=AF_INET;
serveraddr.sin_port=htons(atoi(argv[2]));
serveraddr.sin_addr.s_addr=inet_addr(argv[1]);
//2.绑定套接字 bind (绑定自己的ip和端口,便于别人找到自己)
if(bind(sockfd,(struct sockaddr *)&serveraddr,sizeof(serveraddr))<0)
{
perror("bind err");
return -1;
}
printf("bind ok\n");
//3.listen 监听 将主动套接子变为被动等待
if(listen(sockfd, 5) < 0)
{
perror("listen err");
return -1;
}
printf("listen ok\n");
//4.阻塞等待客户端链接,链接成功返回一个通信文件描述符 accept
acceptfd=accept(sockfd,NULL,NULL);
if(acceptfd<0)
{
perror("accept err");
return -1;
}
printf("accept ok\n");
//5.循环收发消息
char buf[128];
int recvbyte;
while(1)
{
//接收消息
recvbyte=recv(acceptfd,buf,sizeof(buf),0);
if(recvbyte < 0)
{
perror("recv err");
return -1;
}else if(recvbyte ==0)
{
printf("client exit\n");
break;
}
else
{
printf("buf:%s\n",buf);
}
}
close(acceptfd);
close(sockfd);
return 0;
}
客户端段
#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<netinet/ip.h>
#include<arpa/inet.h>
#include<unistd.h>
#include<string.h>
#include<stdlib.h>
int main(int argc, char const *argv[])
{
if(argc != 3)
{
printf("please input %s <ip> <port>\n",argv[0]);
}
//1. 创建套接字 socket
int sockfd;
sockfd = socket(AF_INET,SOCK_STREAM,0);
if(sockfd < 0)
{
perror("socket err");
return -1;
}
printf("socket ok %d\n",sockfd);
//填充ipv4的通信结构体 服务器端ip和端口
struct sockaddr_in serveraddr;
serveraddr.sin_family=AF_INET;
serveraddr.sin_port=htons(atoi(argv[2]));
serveraddr.sin_addr.s_addr=inet_addr(argv[1]);
//2.请求链接 connect (绑定自己的ip和端口,便于别人找到自己)
if(connect(sockfd,(struct sockaddr *)&serveraddr,sizeof(serveraddr))<0)
{
perror("connect err");
return -1;
}
printf("connect ok\n");
//3.循环收发消息
char buf[128];
int recvbyte;
while(1)
{
fgets(buf,sizeof(buf),stdin);
if(buf[strlen(buf)-1]=='\n')
buf[strlen(buf)-1]='\0';
//发送消息
send(sockfd,buf,sizeof(buf),0);
}
close(sockfd);
return 0;
}
注:此服务器仅能接收消息,无法发送消息