Linux(socket通信)--服务端与客户端编程
程序员文章站
2022-06-06 08:38:17
...
server.c
#include <stdio.h> //printf perror
#include <sys/socket.h> //socket blind listen accept connect
#include <unistd.h> //read and write
#include <sys/types.h> //size_t,time_t,pid_t等类型
#include <stdlib.h> //NULL
#include <string.h> //sizeof
#include <netinet/in.h>
#include <netdb.h> //hostnent
#define PORT 2345
#define MAX_QUE_CONN 5 //最大的请求队列
#define BUFFER_SIZE 1024
int main(){
struct sockaddr_in server_sockaddr,client_sockaddr;
int sockfd,client_fd;
int r_bytes;
char buf[BUFFER_SIZE];
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1){
perror("Socket error!\n");
exit(1);
}
/*设置sockaddr_in 结构体中相关参数*/
server_sockaddr.sin_family = AF_INET; //Ipv4
server_sockaddr.sin_port = htons(PORT); //htons:主机字节序(小)-> 网络字节序(大)
server_sockaddr.sin_addr.s_addr = INADDR_ANY; //all ip can connect
memset(server_sockaddr.sin_zero,0,8); //填充0以保持与struct sockaddr同样大小
/*bind sockfd*/
if (bind(sockfd, (struct sockaddr *)&server_sockaddr, sizeof(struct sockaddr)) == -1){
perror("Bind error!\n");
exit(1);
}
/*listen*/
if ( listen( sockfd, MAX_QUE_CONN) == -1){
perror("Listen error!\n");
exit(1);
}
printf("Listening........\n");
/*accept*/
int sin_size;
if ((client_fd = accept(sockfd, (struct sockaddr *)&client_sockaddr, &sin_size)) == -1){
perror("Accept error!\n");
exit(1);
}
/*Recieve message from client*/
memset(buf, 0, sizeof(buf));
if((r_bytes = read(client_fd, buf, BUFFER_SIZE)) == -1){
perror("Read error!\n");
exit(1);
}
printf("Recieve a message: %s\n",buf);
close(sockfd);
return 0;
}
client.c
#include <stdio.h> //printf perror
#include <sys/socket.h> //socket blind listen accept connect
#include <unistd.h> //read and write
#include <sys/types.h> //size_t,time_t,pid_t等类型
#include <stdlib.h> //NULL exit
#include <string.h> //sizeof
#include <netinet/in.h>
#include <netdb.h> //hostnent
#define PORT 2345
#define BUFFER_SIZE 1024
int main(int argc, char **argv){
int sockfd,s_bytes;
struct hostent *host;
char buf[BUFFER_SIZE];
struct sockaddr_in server_sockaddr;
if( argc < 3){
printf("Usage: ./client Hostname(or ip address) Text\n");
exit(1);
}
/*地址解析函数*/
if ((host = gethostbyname(argv[1])) == NULL){
perror("gethostbyname error!\n");
exit(1);
}
memset(buf, 0, sizeof(buf));
sprintf(buf,"%s",argv[2]);
/*Create socket*/
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1){
perror("Socket error!\n");
exit(1);
}
/*设置sockaddr_in 结构体中相关参数*/
server_sockaddr.sin_family = AF_INET; //Ipv4
server_sockaddr.sin_port = htons(PORT); //htons:主机字节序(小)-> 网络字节序(大)
server_sockaddr.sin_addr = *((struct in_addr *)host->h_addr);
memset(server_sockaddr.sin_zero,0,8);
/*connect*/
if((connect(sockfd, (struct sockaddr*)&server_sockaddr, sizeof(struct sockaddr)) == -1)){
perror("Connect error!\n");
exit(1);
}
/*send message to server*/
if((s_bytes = write(sockfd, buf, sizeof(buf))) == -1){
perror("Write error!\n");
exit(1);
}
close(sockfd);
return 0;
}
上一篇: 今天碰到一个可爱的小跑车……