一、流程图
二、代码
服务端:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
int main(int argc, char *argv[])
{
int serv_sock;
int clnt_sock;
struct sockaddr_in serv_addr;
struct sockaddr_in clnt_addr;
socklen_t clnt_addr_size;
char message[] = "hello world!";
serv_sock = socket(PF_INET,SOCK_STREAM,0);
memset(&serv_addr,0,sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port=htons(atoi(argv[1]));
bind(serv_sock,(struct sockaddr*)&serv_addr,sizeof(serv_addr));
listen(serv_sock,5);
clnt_addr_size = sizeof(clnt_addr);
clnt_sock = accept(serv_sock,(struct sockaddr*)&clnt_addr,&clnt_addr_size);
write(clnt_sock,message,sizeof(message));
close(clnt_sock);
close(serv_sock);
return 0;
}
客户端:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
int main(int argc,char* argv[])
{
int sock;
struct sockaddr_in serv_addr;
char message[30];
int str_len;
sock = socket(PF_INET,SOCK_STREAM,0);
memset(&serv_addr,0,sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = inet_addr(argv[1]);
serv_addr.sin_port=htons(atoi(argv[2]));
connect(sock,(struct sockaddr*)&serv_addr,sizeof(serv_addr));
str_len = read(sock,message,sizeof(message)-1);
printf("Message:%s\n",message);
close(sock);
return 0;
}